我有一个问题,我的一些代码使用Spring bean,还有一些常规POJO。
我正在尝试将bean(数据源)注入到POJO的构造函数中(POJO是一个dao)。
代码如下所示,大约:
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 {
以上代码不起作用(dataSource为null
),因为根据this Q&A,
自动装配(来自Dunes评论的链接)在构造对象后发生。
答案 0 :(得分:0)
传递DataSource
,喜欢这应该有效:
public static void main(String[] args) {
AnnotationConfigApplicationContext context = loadSpringConfiguration();
Datasource dataSource = context.getBean(DataSource.class);
SetupDaos setupDaosInstance = new SetupDAOs(dataSource);
setupDaosInstance.setupDAOs();
}
请参阅docs