java - 无法访问 Spring boot application.properties

标签 java spring spring-boot application.properties

我正在尝试访问 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/

相关文章:

mysql - 如何使用hibernate实体管理器在spring boot中调用带有输出参数的MySQL存储过程

spring-boot - 登录后,我被重定向到/robots.txt

java - 在什么情况下,返回响应比编辑 HttpServletResponse 更好?

java - Java有类似数据库的结构吗?

JAVA类转成xml文件

java - 找不到 swagger-resources/configuration/ui 的映射

java - 持久化实体时出现 SQLServerException - 索引超出范围

java - 如何检查 Java 上的 SSLSocket 连接是否正常?

Java:在编译时使用注释生成自定义 Java 代码

spring - 在 Spring 中结合 GET 和 POST 请求方法