Java Spring创建依赖于其他bean的bean
我有以下课程Java Spring创建依赖于其他bean的bean,java,spring,spring-mvc,Java,Spring,Spring Mvc,我有以下课程 public class ConnectionPool { @Autowired private Properties props; @Autowired private Key internalKey; public ConnectionPool{ System.out.println(internalKey); System.out.println(props); } } 我在一个名为ApplicationConfig的类中以以下方式将ConnectionP
public class ConnectionPool {
@Autowired
private Properties props;
@Autowired
private Key internalKey;
public ConnectionPool{
System.out.println(internalKey);
System.out.println(props);
}
}
我在一个名为ApplicationConfig的类中以以下方式将ConnectionPool类创建为bean
@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应用程序启动时是否打印空?我以为Spring负责所有的bean实例化和注入?我还需要做什么 问题是
@Bean
ConnectionPool returnConnectionPool(){
ConnectionPool cPool = new ConnectionPool();
return cPool;
}
在使用新构造显式创建ConnectionPool类时,不允许spring自动连接ConnectionPool类内部的依赖项
为了使它能够工作,我建议您使用一个构造函数,该构造函数接受这两个依赖项,然后将returnConnectionPool方法更改为如下所示
@Bean
ConnectionPool returnConnectionPool(Properties properties, Key key){
ConnectionPool cPool = new ConnectionPool(properties, key);
return cPool;
}
(顺便说一句,这只是一个可能的解决方案,但是spring有很多其他神奇的方法来做同样的事情:)是的,它是
@Configuration公共类应用程序配置{