2017-04-19 48 views
1

我有下面的類春天創建bean依賴於其他豆類

public class ConnectionPool { 

@Autowired 
private Properties props; 

@Autowired 
private Key internalKey; 

public ConnectionPool{ 
    System.out.println(internalKey); 
    System.out.println(props); 
} 
} 

我創建的連接池類是在一個名爲ApplicationConfig類以下方式豆。

@Bean 
ConnectionPool returnConnectionPool(){ 
    ConnectionPool cPool = new ConnectionPool(); 
    return cPool; 
} 

在ApplicationConfig級我也有

@Bean 
Properties returnAppProperties() 
{ 
    Properties props = new Properties(); 
    return props; 
} 

@Bean 
Key returnInternalKey() 
{ 
    Key key = new Key(); 
    return key; 
} 

爲什麼

System.out.println(internalKey); 
    System.out.println(props); 

打印空當的Spring MVC應用程序正在啓動?我以爲春天照顧了所有的bean實例化和注入?我還有什麼要做的?

+0

是的它是'@Configuration public class ApplicationConfig { – user3809938

回答

1

的問題是

@Bean 
ConnectionPool returnConnectionPool(){ 
    ConnectionPool cPool = new ConnectionPool(); 
    return cPool; 
} 

你是不是讓春天的自動裝配類連接池,你正在使用新的結構明確地創造它裏面的依賴關係。

爲了使它工作,我會建議你有一個構造函數,取兩者的依賴關係,然後改變你的returnConnectionPool方法,看起來像這樣

@Bean 
ConnectionPool returnConnectionPool(Properties properties, Key key){ 
    ConnectionPool cPool = new ConnectionPool(properties, key); 
    return cPool; 
} 

(PS這僅僅是一個可能的解決方案,但春天的一個有很多其他的神奇的方式來做同樣的東西:))