@Autowired Environment 始终为空。

10

我有一个简单的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


有没有可能与缺少默认构造函数有关?否则,您可以尝试删除@PropertySource,仅供测试。 - Jos
如果我删除它,应该看到什么? 缺少默认构造函数吗? Word2VecRestController 是否定义了它? - Stefan Falk
@redflar3 噢,这是不是在构造函数中始终为 null,就像使用 @Value 声明的任何内容一样? - Stefan Falk
抱歉,我表达不够清晰,两者都是无关的建议。通过删除,您可以让Spring使用其智能来获取属性文件。 - Jos
@redflar3 不,属性文件实际上已经被找到了。我认为这是我的错 - 在构造函数中似乎这也是 null - Stefan Falk
显示剩余5条评论
2个回答

16

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

@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;
    }

}

注意: 如果你使用Spring Boot,就不需要添加@PropertySource("classpath:application.properties"),因为这个操作已经自动完成。


0

添加

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

启用PropertySourcesPlaceholderConfigurer到您的配置中。重要的是,这必须是一个静态方法!

例如:

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

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接