Spring bean与运行时构造函数参数 [英] Spring bean with runtime constructor arguments

查看:455
本文介绍了Spring bean与运行时构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a Spring bean in Spring Java configuration with some constructor arguments passed at runtime. I have created the following Java config, in which there is a bean fixedLengthReport that expects some arguments in constructor.

@Configuration
Public AppConfig {

@Autowrire
Dao dao;

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

但我收到错误 sourceSystem 无法' t wire因为没找到豆子。如何使用运行时构造函数参数创建bean?

But i am getting error that sourceSystem couldn't wire because no bean found. How can I create bean with runtime constructor arguments?

我使用的是Spring 4.2

I am using Spring 4.2

推荐答案

你可以使用next aproach:

You can use next aproach:

@Configuration
public class AppConfig {

   @Autowired
   Dao dao;

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

@Lazy 意味着Spring不会在启动时实例化这个bean,但会在以后按需执行。现在,要获取这个bean的实例,你必须做下一步:

@Lazy means, that Spring will not instantiate this bean right on start, but will do it later on demand. Now, to get instance of this bean you have to do next:

@Controller
public class ExampleController{

   @Autowired
   private BeanFactory beanFactory;

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

注意,因为你的bean无法实例化开始,你不能直接自动装配你的bean。否则@Lazy注释将被忽略,Spring将尝试自己创建bean的实例。下一次使用将导致错误:

Note, because of your bean can not be instantiated on start, you must not autowire your bean directly. Otherwise @Lazy annotation will be ignored, and Spring will try to create instance of bean by himself. Next usage will cause an error:

@Controller
public class ExampleController{

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

}

这篇关于Spring bean与运行时构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆