@Autowired Environment始终为null

时间:2017-01-24 20:26:05

标签: spring

我有一个简单的RestController

@RestController
@PropertySource("classpath:application.properties")
public class Word2VecRestController {

    private final static Logger LOGGER = Logger.getLogger(Word2VecRestController.class);

    // @Resource is not working as well
    @Autowired
    Environment env;

    // This is working for some reason 
    // but it's null inside the constructor
    @Value("${test}") 
    String test;

    public Word2VecRestController() {

        LOGGER.info(env.getProperty("test"));

        System.out.println("");

    }

    @GetMapping("/dl4j/getWordVector")
    public ResponseEntity<List<Double[]>> getWordVector(String word) {
        return null;
    }

}

问题是,env总是null。我曾经在某个地方看到我可以尝试使用@Resource代替@Autowired,但这并没有帮助。

application.properties

test=helloworld

我试图使用

@Value("${test}")
String test;

但问题是在我需要的对象构造过程中这些是null

2 个答案:

答案 0 :(得分:4)

在调用构造函数之后,Spring 完成字段注入。这就是Environment构造函数中Word2VecRestController为空的原因。如果在构造函数中需要它,可以尝试构造函数注入:

@RestController
@PropertySource("classpath:application.properties")
public class Word2VecRestController {

    private final static Logger LOGGER = Logger.getLogger(Word2VecRestController.class);

    @Autowired
    public Word2VecRestController(Environment env, @Value("${test}") String test) {

        LOGGER.info(env.getProperty("test"));

        System.out.println("");

    }

    @GetMapping("/dl4j/getWordVector")
    public ResponseEntity<List<Double[]>> getWordVector(String word) {
        return null;
    }

}

PS :如果您使用Spring Boot,则不需要@PropertySource("classpath:application.properties"),这是自动完成的。

答案 1 :(得分:0)

添加

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

为您的配置启用PropertySourcesPlaceholderConfigurer。重要的是,这必须是static方法!

例如:

@Configuration
@PropertySource("classpath:application.properties")
public class SpringConfig {

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

}