【问题标题】:Spring : Autowired Environment is nullSpring:自动装配环境为空
【发布时间】:2014-07-30 12:27:41
【问题描述】:

春季版: 3.2.6.RELEASE

我正在尝试通过 Spring 中的 Environment 类访问属性文件中的属性,但自动连接的 Environemnt 始终为 null

@Configuration
@PropertySource("classpath:server.properties")
@EnableNeo4jRepositories(basePackages = "com.repositories")
public class Neo4jConfig extends Neo4jConfiguration {

     @Autowired
     private Environment env;

    @Bean(destroyMethod = "shutdown")
    public GraphDatabaseService graphDatabaseService() {
        return new SpringRestGraphDatabase(env.getRequiredProperty("neo4j.server.url"));
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()             {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

@Configuration
@Import({JMSConfig.class, Neo4jConfig.class})
@ComponentScan(basePackageClasses=BeansPackageMarker.class)
public class ApplicationConfig {

}

  • @Value 工作正常,所以我确信 Spring 能够找到我的属性文件,并用属性文件中的相应值正确替换属性占位符

    现在我只想使用Environment 来获取属性值而不是${...},但env 始终是null

    这是我创建ApplicationContext的方式

    ApplicationContext appCtx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
    
  • 【问题讨论】:

    • 我不相信是这种情况。你能发布一个显示 NPE 的堆栈跟踪吗?

    标签: spring


    【解决方案1】:
    @Autowired(required = true)
    @Override
    public void setGraphDatabaseService(GraphDatabaseService graphDatabaseService) {
        super.setGraphDatabaseService(graphDatabaseService);
    }
    

    将上述方法添加到 Neo4jConfig.java

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2015-09-30
      • 2016-05-25
      • 2015-07-28
      • 2014-07-08
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      相关资源
      最近更新 更多