I have a problem, where some of my code uses Spring beans, and some, regular POJOs.
I'm trying to inject a bean (datasource) into a POJO's constructor (POJO is a dao).
The codes looks like this, approximately:
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 {
The above code doesn't work (dataSource is null
), because according to this Q&A,
Autowiring (link from Dunes comment) happens after the construction of an object.