2017-04-19 49 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这仅仅是一个可能的解决方案,但春天的一个有很多其他的神奇的方式来做同样的东西:))