Spring配置 - 需要自动连接的bean吗?

时间:2018-01-05 07:58:35

标签: spring spring-boot configuration autowired

我遇到原型bean包含单例bean的情况。为了实现它,我必须创建2个配置类。是否可以将我的2个配置类合并为一个?

Singleton类:

public class MySingleton {
}

原型类:

public class MyPrototype {

    private MySingleton b;

    public MyPrototype(MySingleton b) {
       this.b = b;
   }
}

配置类1:

@Configuration
public class ConfigClassA {

   @Bean
   public MySingleton myBean() {
       return new MySingleton();
   }

}

配置类2:

@Configuration
public class ConfigClassB {

   @Autowired
   public MySingleton mb;

   @Bean
   @Scope("prototype")
   public MyPrototype myPrototype() {
       return new MyPrototype(mb);
   }

}

1 个答案:

答案 0 :(得分:1)

试试这个:

@Configuration
public class ConfigClass {

   @Bean
   public MySingleton myBean() {
     return new MySingleton();
   } 

   @Bean
   @Scope("prototype")
   public MyPrototype myPrototype(MySingleton myBean) {
     return new MyPrototype(myBean);
   }
}

BeanFactory应该在创建原型bean时搜索MySingleton类型的bean,并将其注入方法myPrototype