如何在构造函数中为不是Spring-ified的对象使用autowired参数?

时间:2016-09-26 16:52:18

标签: java spring constructor autowired pojo

我有一个问题,我的一些代码使用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评论的链接)在构造对象后发生。

如果“dao1”必须保留为POJO并且不是Spring创建的bean,那么有什么方法可以将autowired bean“dataSource”正确地注入其构造函数中吗?

1 个答案:

答案 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