Spring创建一个依赖于其他bean的bean

时间:2017-04-19 21:52:23

标签: java spring spring-mvc

我有以下课程

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

我在一个名为ApplicationConfig的类中以下列方式将ConnectionPool类创建为bean。

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

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

在ApplicationConfig类中我也有

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

为什么

{{1}}

在Spring mvc应用程序启动时打印null?我以为Spring负责所有的bean实例化和注入?还有什么我需要做的?

1 个答案:

答案 0 :(得分:1)

问题是

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

您不会让Spring自动装配ConnectionPool类中的依赖项,因为您使用新构造显式创建它。

为了使它工作,我建议你有一个构造函数,它接受两个依赖项,然后将returnConnectionPool方法更改为这样

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

(P.S。这只是可能的解决方案之一,但春天有很多其他神奇的方法来做同样的事情:))

相关问题