我有一個問題,其中一些代碼使用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調用保留。 –