【问题标题】:Get bean with dynamic constructor arguments获取带有动态构造函数参数的bean
【发布时间】:2015-11-22 00:18:51
【问题描述】:

我有一个 spring 组件,它有一个 @Autowired 构造函数,它从 @Value 注释中获取其参数。像这样:

@Component
public class MyImplClass implement MyInterface
...
public MyImplClass(@Value("${prop.name}") final String name, @Value("${prop.value}") final String value) {
...
}
...

在另一个类中,我像这样自动装配这种类型

@Autowired
protected MyInterface _myInterface;

现在我需要获取传递给构造函数的动态生成值(在运行时生成)的 MyInterface bean。我尝试使用AbstractBeanFactory,但这不起作用。我该怎么做?

【问题讨论】:

    标签: java spring autowired


    【解决方案1】:

    您可以像这样在 Spring 配置中生成一个 bean:

    @Bean
    public MyInterface getMyInterfaceBean() {
        // Calculate arg values
        String arg1 = ...;
        String arg2 = ...;
        return new MyImplClass(arg1, arg2);
    }
    

    更好的解决方案是更改MyImplClass 的构造函数以接收一个知道如何加载所需值的配置对象。

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 2019-03-10
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2011-12-26
      • 2021-10-25
      相关资源
      最近更新 更多