【问题标题】:Plain Data Bean, Caller of Autowired Bean (a @Component), Sees NULL普通数据 Bean,Autowired Bean(@Component)的调用者,看到 NULL
【发布时间】:2016-08-31 01:18:01
【问题描述】:

新手春季问题。我有一个正确注释的 @Component 类,它为我带来了我的环境配置。

@Component
public class EnvConfig { 
   //...
}

因为它是一个@Component,它会被自动注入提取出来。

但是这个类的调用者是一个普通的数据bean。普通数据 bean 有一个特殊的实用方法需要访问这个类。

public class EmployeeBean {

   @Autowired
   EnvConfig envConfig;

   //...

   public void getSpecialInfo() 
   {
       envConfig.method1();
       envConfig.method2();
   }
}
当我调试这个方法时,

envConfig 是 NULL

所以 Autowired 对象的调用者需要是@Component、@Service 或@Repository?

【问题讨论】:

    标签: spring


    【解决方案1】:

    或多或少,是的。 Spring 显然可以自动装配它管理的对象(换句话说,“Spring Beans”)——否则它怎么能做到呢?所以,如果你自己创建一个对象(new ...),那么它就不是一个“spring bean”,只是一个随机对象,Spring 无法控制它——它也不能自动在其中自动装配一些东西。

    这样做的一种方法是将它们设为@Component 等,然后通过 Spring 的组件扫描找到它们。

    创建 Spring bean 的其他方法是 JavaConfig(通过 @Bean)、XML 配置(通过 <bean .../>)和其他(例如通过 PreProcessors,但开始变得深奥)。

    当然,您也可以使用对 Spring 应用程序上下文的一些静态访问来让您自己的对象访问 Spring bean - 但这并不是一个真正好的方法。

    【讨论】:

    • 记得将注解的类放在通过@ComponentScan/<context:component-scan>定义的包中
    • 或者,可以使用 Spring Boot 的强大功能而不必太在意这些东西 ;-)
    • 但是应该注意限制:) AFAIK @SpringBootApplication 使用 @ComponentScan 而没有 basePackage 参数。因此,可以将 Application 放在“错误”的位置(例如嵌套包),它可能无法神奇地在整个应用程序(根)包上工作;)
    • 没错,这就是我写“太多”的原因。一点点思考总是好的;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2014-11-29
    相关资源
    最近更新 更多