2011-11-18 65 views
2

我创建了一个Spring @Configuration注释类,我想为它自动装载一个ResourceLoader,以便我可以在一个@Bean方法中使用它来查找由串。当我运行应用程序并初始化上下文时,我得到一个NPE访问autowired字段,并且在调试模式下它显示为空/未设置。我错在期待resourceLoader存在吗?我错误地断言配置bean的自动装配发生在其方法被调用之前? XML配置装载这个bean被打上<方面:注解配置/>Spring @Configuration类需要自动装配

@Configuration 
public class ClientConfig { 

    @Autowired 
    private ResourceLoader resourceLoader; 

    public @Bean 
    String configHome() { 
     return System.getProperty("CONFIG_HOME"); 
    } 

    public @Bean 
    PropertiesFactoryBean appProperties() { 
     String location = "file:" + configHome() + "/conf/webservice.properties"; 
     PropertiesFactoryBean factoryBean = new PropertiesFactoryBean(); 
     factoryBean.setLocation(resourceLoader.getResource(location)); 

     return factoryBean; 
    } 
} 

回答

5

我不知道这是否是一个bug或者是预期的行为。有时它对我有用,有时不适用。无论如何,有另一种实现你想要的方式:

public @Bean PropertiesFactoryBean appProperties(ResourceLoader resourceLoader) { 
    // resourceLoader is injected correctly 
    ... 
}