0

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.

If "dao1" must stay as a POJO and not be a Spring created bean, is there any way I can properly inject autowired bean "dataSource" into its constructor somehow?

Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327

1 Answers1

0

Passing the DataSource around, like this should work:

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = loadSpringConfiguration();
    Datasource dataSource = context.getBean(DataSource.class);
    SetupDaos setupDaosInstance = new SetupDAOs(dataSource);
    setupDaosInstance.setupDAOs();
}

see https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/support/AbstractApplicationContext.html#getBean-java.lang.Class-

  • Note that I would, personaly, use a bean for DaoType, static is bad –  Sep 26 '16 at 17:02