我有一个问题,其中一些代码使用Spring bean,还有一些常规POJO。如何在构造函数中为不是Spring的对象使用autowired参数?
我试图将一个bean(数据源)注入到POJO的构造函数(POJO是一个道)。
的代码看起来是这样的,近似为:
public class MyAppClass {
public static void main(String[] args) {
// xxx
AnnotationConfigApplicationContext context = loadSpringConfiguration();
SetupDaos setupDaosInstance = new SetupDAOs();
setupDaosInstance.setupDAOs(); // This is where DAO constructors live
}
public class SetupDAOs {
public static DaoType dao1;
// There is a reason why dao1 isn't a bean, that aren't obvious from minimal example
// Please don't post answers saying
// "you have an X-Y problem, convert dao1 into a bean"
public void setupDAOs() {
dao1 = new DaoType(); // We don't pass datasource here,
}
}
public class DaoType extends JdbcTemplate {
// This is where trouble starts
@Autowired ComboPooledDataSource dataSource;
// PROBLEM! Inside the constructor, "dataSource" isn't autowired yet!
public DaoType() {
super();
setDataSource(dataSource);
}
}
// And in one of the Bean config classes
@Bean
public ComboPooledDataSource loadDataSource() throws Exception {
上面的代码不工作(数据源是null
),因为根据this Q&A,
自动装配(从沙丘评论链接)发生在建造物体之后。
如果“新”了一个对象自己,春天是不是在所有参与,在任何时候。 –
我可以通过'AnnotationConfigApplicationContext' +'getBean()'以某种方式调用它吗? – DVK
是的。它仍然没有建筑物的属性。您可以让它们构造函数参数或在生命周期的稍后一段时间将setDataSource调用保留。 –