【问题标题】:Autowired spring bean is nul自动装配的弹簧豆为空
【发布时间】:2017-03-12 03:06:33
【问题描述】:

我定义了一个简单的类,它包含我的 elasticsearch 客户端的配置属性(称为 ElasticClientConfig.java)。

我为我的开发、生产和测试环境定义了一个配置。每个配置文件都有一个方法,该方法返回一个 ElasticClientConfig 类型的 bean,并使用特定于环境的参数构建一个 MyConfig 对象。这是开发版本:

@Configuration
@Profile("dev")
public class DevConfig {

    @Bean
    public ElasticClientConfig getElasticClientConfig(){
          //build the ElasticSearchConfig and return it
    }

}

我在 web.xml 文件中将我的活动配置文件设置为“dev”:

   <context-param>
      <param-name>spring.profiles.active</param-name>
      <param-value>dev</param-value>
   </context-param>

我使用@Autowired 注解注入了一个 ElasticClientConfig 对象,但它为空。关于我可以检查什么的任何想法?我的 spring-servlet.xml 文件很简单:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.elasticapp" />

    <mvc:annotation-driven />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    <bean class="com.elasticapp.client.ElasticClient"/>
</beans>

ElasticClient 是我将 ElasticClientConfig 注入的类。

【问题讨论】:

    标签: java spring spring-mvc elasticsearch


    【解决方案1】:

    我忘记了依赖注入是如何工作的,意识到我试图访问构造函数中的自动装配属性。决定使用@PostConstruct,完美运行!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2014-07-08
      • 2016-09-27
      • 1970-01-01
      相关资源
      最近更新 更多