Spring:Autowired Environment为null

时间:2014-07-30 12:27:41

标签: spring

春季版: 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);
    
  • 1 个答案:

    答案 0 :(得分:0)

    @Autowired(required = true)
    @Override
    public void setGraphDatabaseService(GraphDatabaseService graphDatabaseService) {
        super.setGraphDatabaseService(graphDatabaseService);
    }
    

    将上述方法添加到Neo4jConfig.java