带有运行时构造函数参数的Spring bean


问题内容

我想在 Spring Java配置中 创建一个Spring bean,并在运行时传递一些构造函数参数。我创建了以下Java配置,其中有一个bean
fixedLengthReport ,它在构造函数中需要一些参数。

@Configuration
public class AppConfig {

    @Autowrire
    Dao dao;

    @Bean
    @Scope(value = "prototype")
    **//SourceSystem can change at runtime**
    public FixedLengthReport fixedLengthReport(String sourceSystem) {
         return new TdctFixedLengthReport(sourceSystem, dao);
    }
}

但是我收到错误消息, 表明 未找到bean 导致 sourceSystem 无法连接。如何使用运行时构造函数参数创建bean?

我正在使用Spring 4.2


问题答案:

您可以将原型bean与一起使用BeanFactory

@Configuration
public class AppConfig {

   @Autowired
   Dao dao;

   @Bean
   @Scope(value = "prototype")
   public FixedLengthReport fixedLengthReport(String sourceSystem) {
       return new TdctFixedLengthReport(sourceSystem, dao);
   }
}

@Scope(value = "prototype")意味着Spring不会在启动时立即实例化Bean,而是稍后在需要时进行实例化。现在,要定制原型bean的实例,您必须执行以下操作。

@Controller
public class ExampleController{

   @Autowired
   private BeanFactory beanFactory;

   @RequestMapping("/")
   public String exampleMethod(){
      TdctFixedLengthReport report = 
         beanFactory.getBean(TdctFixedLengthReport.class, "sourceSystem");
   }
}

注意,由于无法在启动时实例化bean,因此不能直接自动装配bean。否则,Spring将尝试实例化bean本身。这种用法将导致错误。

@Controller
public class ExampleController{

   //next declaration will cause ERROR
   @Autowired
   private TdctFixedLengthReport report;

}