我正在尝试访问 Spring Boot 应用程序的服务类中的 application.properties
值。但每次值都是null,所以它会抛出NullPointException
。我可以在 Controller 类中获得正确的端口值(如果我在 Controller 中添加@Autowired),但不能在服务类中获得正确的值。需要进行哪些更改才能使该属性在整个应用程序中可用?
Controller 看起来像:
@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
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
实例从 Controller 传递到服务的默认构造函数,但它不起作用。当我调试时,值在应用程序启动时持续存在,但当我进行其余 Web 服务 POST 调用时,它为 null。
最佳答案
在您的 Controller MyController
中,您必须注入(inject)服务,替换:
MyService ss = new MyService();
作者:
@Autowired
MyService ss;
此外,您还可以使用 Spring 中的 @Value
注释来从 application 加载属性,而不是使用
文件。看一下这段代码:ApplicationProperties
类。 .properties
import org.springframework.beans.factory.annotation.Value;
// ...
@Service
public class MyService {
@Value("${port}")
private String port;
// ...
}
关于java - 无法访问 Spring boot application.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54226279/