【发布时间】:2019-07-02 17:52:39
【问题描述】:
我正在尝试访问 Spring Boot 应用程序服务类中的 application.properties 值。但是每次值都是空的,所以它抛出NullPointException。我可以在控制器类中获得正确的端口值(如果我在控制器中添加@Autowired),但不能在服务类中。需要进行哪些更改才能使此属性在整个应用程序中可用?
控制器看起来像:
@RestController
public class MyController {
MyService ss = new MyService();
@RequestMapping(value = "/myapp/abcd", method = RequestMethod.POST, consumes = {"application/json"})
public ResponseMessage sendPostMethod(@RequestBody String request) {
log.debug(" POST Request received successfully; And request body is:"+ request);
ResponseMessage response = ss.processRequest(request);
return response;
}
}
而Service类是:
@Service
public class MyService {
private ApplicationProperties p;
@Autowired
public setProps(ApplicationProperties config) {
this.p = config;
}
public ResponseMessage processRequest(String request) {
System.out.println("Property value is:"+ p.getPort());
}
}
ApplicationProperties.java 看起来像:
@Component
@Getter
@Setter
@ConfigurationProperties
public class ApplicationProperties {
String port;
}
最后,application.properties 文件有:
port=1234
我什至尝试过将ApplicationProperties 实例从控制器传递到服务的默认构造函数,但它不起作用。当我调试时,值在应用程序启动时保持不变,但是当我进行休息 Web 服务 POST 调用时,它为空。
【问题讨论】:
-
这一行是问题所在。
MyService ss = new MyService();你应该自动装配它而不是使用new创建 -
你的意思是“@Autowired MyService ss;” ?
-
是的。如果您使用 new 创建一个对象。不是春豆
-
对。谢谢...
标签: java spring spring-boot application.properties