2012-09-14 3 views
2

스프링 구성 요소 스캔이 작동하지 않는 것처럼 보입니다. 나는 Spring 3.1과 Tomcat 7.0을 사용하고있다. 나는이 같은 클래스가스프링 구성 요소 스캔이 작동하지 않습니다.

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" 
xmlns:p="http://www.springframework.org/schema/p" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
      http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> 

    <context:annotation-config/> 
    <context:component-scan base-package="com.abc"/> 

    <bean id="myBean" class="com.efg.test.MyBean" /> 
</beans> 

:처럼 내 applicationContext.xml 모양을

이는 내가 테스트는 웹 어플리케이션의 시작에 Spring에 의해 초기화 될 것으로 예상했다

package com.abc.test 

@Component 
class Test { 
    @Autowired 
    private static MyBean myBean; 

    public static MyBean getMyBean() { return myBean; } 
    public static void setMyBean(MyBean bean) { myBean = bean; } 
} 

그리고 myBean이 자동으로 주입 될 것이므로 Test (정적) 메소드를 호출하면 myBean에 대한 null이 아닌 참조가 생깁니다.

그러나 myBean은 주입되지 않으며 항상 null입니다 (myBean 자체는 싱글 톤으로 초기화되고 주입되지 않습니다). 이 기능을 사용하려면 내가해야 할 일이 무엇이 있습니까? applicationContext.xml에 Test 클래스를 추가하면 모든 것이 작동합니다. 내 생각 엔 Test는 Spring에 의해 초기화되지 않았기 때문에 유선이 아닙니다.

는 업데이트 : I의 (a JSP 함수로 호출이 클래스의 방법) 정적 컨텍스트에서 autowire가 필드에 액세스 할 수 있어야합니다 , 따라서 정적이어야합니다.

답변

7

스프링의 아이디어는 클래스 (즉, 객체)의 인스턴스을 초기화하고 구성한다는 것입니다. 실제로 정적 필드는 어떤 인스턴스에도 속하지 않으므로 static 필드에는 @Autowired을 적용 할 수 없으며 접근 방법도 static이 아니어야합니다.

+0

좋아, 나는 더 많은 컨텍스트를 제공해야한다. 사용자 정의 JSP 함수로 불리기 때문에 정적 인 것이 필요하다. 내 설명을 업데이트했습니다. 그러나 감사합니다, 이것은 내가 가지고 있지 않은 정보입니다 :) – Tim

+0

다음과 같이 작동합니다. 이제는 클래스의 인스턴스를 싱글 톤으로 저장하고 스프링이 삽입 된 객체에 액세스해야했습니다. – Tim

1

스프링으로 정적 필드를 직접 주입 할 수 있다고 생각하지 않습니다. this을 참조하십시오.

관련 문제