gpt4 book ai didi

spring - @Autowired Environment 始终为空

转载 作者:行者123 更新时间:2023-12-03 15:25:15 25 4
gpt4 key购买 nike

我有一个简单的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但这没有帮助。

应用程序属性 :
test=helloworld

我试过用
@Value("${test}")
String test;

但这里的问题是这些是 null在我需要它的对象的构建过程中。

最佳答案

字段注入(inject)由 Spring 在调用构造函数后完成。这就是为什么EnvironmentWord2VecRestController 中为空构造函数。如果在构造函数中需要,可以尝试构造函数注入(inject):

@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") ,这是自动为您完成的。

关于spring - @Autowired Environment 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41838368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com