2016-09-26 88 views
0

我有一个问题,其中一些代码使用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

自动装配(从沙丘评论链接)发生在建造物体之后。

如果“具有Dao1”必须保持作为一个POJO,而不是成为一个春天创建豆,是有什么办法妥善能以某种方式注入自动装配Autowired豆“数据源”到它的构造?

+1

如果“新”了一个对象自己,春天是不是在所有参与,在任何时候。 –

+0

我可以通过'AnnotationConfigApplicationContext' +'getBean()'以某种方式调用它吗? – DVK

+0

是的。它仍然没有建筑物的属性。您可以让它们构造函数参数或在生命周期的稍后一段时间将setDataSource调用保留。 –

回答

0

薪火DataSource左右,这应该工作:

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

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

+0

请注意,我个人会使用DaoType的bean,static是不好的 – 2016-09-26 17:02:05

相关问题