Spring bean与运行时构造函数参数

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

@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无法连接,因为没有找到bean。 如何使用运行时构造函数参数创建bean?

我使用的是Spring 4.2

你可以使用下一个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的实例,您必须执行下一步:

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

注意,由于你的bean无法在启动时实例化,你不能直接自动assembly你的bean。 否则@Lazy注释将被忽略,Spring将尝试自己创建bean的实例。 下一次使用会导致错误:

 @Controller public class ExampleController{ //next declaration will cause ERROR @Autowired private TdctFixedLengthReport report; } 

你的代码看起来很好,用参数获取原型使用BeanFactory#getBean(String name,Object … args)方法。

看看Spring Java Config:如何使用运行时参数创建原型范围的@Bean? BeanFactory#getBean(String name,Object … args)将是您正在寻找的。

我想你的IDEA(在我的情况下是IntelliJ IDEA版本15)给你错误,它不是运行时/编译时错误。

在IntelliJ中,您可以更改弹簧检查的设置。

  • 转到文件 – >设置。
  • 在搜索框中键入检查。
  • 转到Spring Core-> Code-> Autowire for Bean Classes。
  • 从“错误”更改为“弱警告”