복붙노트

[SPRING] 컨트롤러에서 작동하지만 다른 클래스에서는 작동하지 않는 Spring @ Autowired messageSource?

SPRING

컨트롤러에서 작동하지만 다른 클래스에서는 작동하지 않는 Spring @ Autowired messageSource?

새로운 업데이트 : 2010 년 12 월 31 일 8:15 PM 매우 더러운 수정이지만 일시적으로 messageSource를 작동시키는 방법입니다. 'MessageSource'를 Message 클래스에 전달하도록 컨트롤러 클래스를 변경했으며 메시지를 검색 할 수있었습니다. 아래 클래스 정의를 검토하고 도움이 필요할 수있는 추가 정보를 알려주십시오. 당신이 제공하는 모든 도움에 정말 감사드립니다.

2010 년 12 월 31 일 오후 3시 어노테이션을 통해 messageSource를 설정하는 데 성공하지 못했기 때문에 servlet-context.xml을 통해 messageSource 삽입을 구성하려고 시도했습니다. 나는 여전히 messageSource를 null로 가지고있다. 더 자세한 정보가 필요하면 알려주세요. 제공 할 것입니다. 미리 도움을 주셔서 감사합니다.

servlet-context.xml
<beans:bean id="message"
    class="com.mycompany.myapp.domain.common.message.Message">
    <beans:property name="messageSource" ref="messageSource" />
</beans:bean>

Spring은 스프링 초기화에 대한 아래의 정보 메시지를 제공한다.

INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning

INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'message': replacing [Generic bean: class [com.mycompany.myapp.domain.common.message.Message]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [C:\springsource\tc-server-developer-2.1.0.RELEASE\spring-insight-instance\wtpwebapps\myapp\WEB-INF\classes\com\mycompany\myapp\domain\common\message\Message.class]] with [Generic bean: class [com.mycompany.myapp.domain.common.message.Message]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]]

INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring

INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1c7caac5: defining beans [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,xxxDao,message,xxxService,jsonDateSerializer,xxxController,homeController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,tilesViewResolver,tilesConfigurer,messageSource,org.springframework.web.servlet.handler.MappedInterceptor#1,localeResolver,org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,validator,resourceBundleLocator,messageInterpolator]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@4f47af3

아래 3 가지 클래스의 메시지 소스에 대한 정의가 있습니다. 디버그 모드에서 xxxController 클래스에서 messageSource가 org.springframework.context.support.ReloadableResourceBundleMessageSource로 초기화된다는 것을 알 수 있습니다. @Repository를 사용하여 Message 클래스에 @Component 및 xxxHibernateDaoImpl을 주석으로 추가했습니다. 또한 servlet-context.xml에 컨텍스트 네임 스페이스 정의를 포함했습니다. 그러나 Message 클래스와 xxxHibernateDaoImpl 클래스에서 messageSource는 여전히 null입니다.

xxxController 클래스에서 Spring이 두 다른 클래스의 messageSource를 초기화하지 않는 이유는 무엇입니까?

@Controller
public class xxxController{
    @Autowired
    private ReloadableResourceBundleMessageSource messageSource;
}

@Component
public class Message{
 @Autowired
 private ReloadableResourceBundleMessageSource messageSource;
}

@Repository("xxxDao")
public class xxxHibernateDaoImpl{
 @Autowired
 private ReloadableResourceBundleMessageSource messageSource;
}

<beans:beans
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <beans:property name="basename" value="/resources/messages/messages" />
</beans:bean>   

    <context:component-scan base-package="com.mycompany.myapp"/>
</beans>

해결법

  1. ==============================

    1.Spring은 null 값 필드를 가져 오는 클래스에 대해 알지 못합니다. 당신은 Spring을 애플 리케이션 컨텍스트에서 bean으로 정의하거나 클래스를 @Component로 주석함으로써 Spring에 대해 알릴 수있다.

    Spring은 null 값 필드를 가져 오는 클래스에 대해 알지 못합니다. 당신은 Spring을 애플 리케이션 컨텍스트에서 bean으로 정의하거나 클래스를 @Component로 주석함으로써 Spring에 대해 알릴 수있다.

    당신의 첫 번째 클래스가 autowire를 올바르게 얻는 이유는 클래스가 @Controller로 정확하게 주석을 달았 기 때문입니다.

  2. ==============================

    2.기본 패키지를 수정하십시오. 스프링이 모든 응용 프로그램 클래스 com.mycompany.myapp를 검사하도록하지 마십시오 (시작 시간이 더 길어집니다).

    기본 패키지를 수정하십시오. 스프링이 모든 응용 프로그램 클래스 com.mycompany.myapp를 검사하도록하지 마십시오 (시작 시간이 더 길어집니다).

    컨트롤러 클래스가 패키지에 있다고 가정합니다. com.mycompany.myapp.controller 및 com.mycompany.myapp.services 패키지의 서비스 클래스 (@component, @repository로 주석 됨)

    이것을 [servlet-name] -servlet.xml (Dispatcher 컨텍스트 파일)에 추가하십시오.

    <context:component-scan base-package="com.mycompany.myapp.controller" />
    

    다른 한편, servlet-context.xml (contextloaderListener에 의해로드 된 응용 프로그램 컨텍스트로 간주 됨)을 열고 다음을 추가하십시오.

    <context:component-scan base-package="com.mycompany.myapp.services" />
    

    당신이했던 것처럼 당신의 messageSource에 대한 선언이 이어졌다.

    자동 응답되는 곳마다 하나의 messageSource가 삽입됩니다. Dispatcher-context-file에 정의 된 내용은 응용 프로그램 컨텍스트 파일에서 선언 된 다른 Bean을 볼 수는 있지만 반대로는 볼 수 없기 때문에 작동해야합니다.

  3. from https://stackoverflow.com/questions/4567512/spring-autowired-messagesource-working-in-controller-but-not-in-other-classes by cc-by-sa and MIT license