我有一个简单的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
在我需要它的对象的构造过程中。
在构造函数被调用之后,Spring会进行字段注入。这就是为什么Environment
在Word2VecRestController
构造函数中为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] 删除。
我来说两句