【问题标题】:Is it possible to use a @Resource instance defined in the same @Configuration class?是否可以使用在同一 @Configuration 类中定义的 @Resource 实例?
【发布时间】:2023-03-12 07:01:01
【问题描述】:

我有一个类似的例子

Other 类需要 MyBean 的实例,所以我正在创建一个属性并在创建 Other 时使用该属性

@Configuration 
public SomeClass {

     @Resource 
     private MyBean b;

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb"); // NPE
         return b;
     }

     @Bean 
     public Other other() {
         Other o = new Other(o);
         return o;
     }
}

但是我在初始化 myBean 对象时得到了 NullPointerException,我猜这是因为 env 属性在那时还没有被连接。

如果我不使用 bean 并直接使用该方法,一切正常。

@Configuration 
public SomeClass {

     @Autowired
     Environment env;

     @Bean
     public MyBean myBean() {
         MyBean b = new MyBean();
         b.foo(env.getProperty("mb"); // NPE
         return b;
     }

     @Bean 
     public Other other() {
         Other o = new Other(myBean());
         return o;
     }
}

是因为我在同一个@Configuration 类中定义了@Bean

【问题讨论】:

  • 我猜如果您在b 字段中替换@Autowired@Resource 注释它可以正常工作?
  • @XtremeBiker 好吧,那行得通。您可以将其发布为答案吗?

标签: java spring dependency-injection


【解决方案1】:

尽管它作为一个概念性问题很有趣,但使用 Spring Java 配置的方法只是将所需的 bean 作为参数传递,因此您可以避免将 bean 自动装配为配置类的字段。如果您的任何 bean 碰巧需要 MyBean 实例,只需将其作为参数提供:

 @Bean 
 public Other other(MyBean myBean) {
     Other o = new Other(myBean);
     return o;
 }

从您的配置类调用@Bean 带注释的方法也没有问题,就像您在第二个代码sn-p 中所做的那样,因为它们是proxied and cached,因此它们不会创建不必要的实例。但是,我倾向于遵循上面的代码,因为它可以让开发人员快速了解所需的依赖项。

话虽如此,对于您的具体问题@Autowired 可以代替@Resource,但是在@Configuration 类中使用它们中的任何一个都没有意义。只需使用本地方法参数即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多