@Autowired Environment始终为null

斯蒂芬·福克

我有一个简单的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在我需要它的对象的构造过程中。

克里斯多夫·L

在构造函数被调用之后,Spring会进行字段注入这就是为什么EnvironmentWord2VecRestController构造函数中为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;
    }

}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章