【问题标题】:Not able to access Spring boot application.properties无法访问 Spring Boot application.properties
【发布时间】: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


【解决方案1】:

在您的控制器MyController 中,您必须注入服务,替换:

MyService ss = new MyService();

作者:

@Autowired
MyService ss;

此外,您可以使用 Spring 中的 @Value 注释而不是 ApplicationProperties 类来从 application.properties 文件加载属性。看看这段代码:

import org.springframework.beans.factory.annotation.Value;
// ...

@Service
public class MyService {

    @Value("${port}")
    private String port;

    // ...
}

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,但出于其他原因。 对我来说,解决方案是添加弹簧。在 application.properties 中的每个参数之前。 所以例如“spring.flyway.user=root”。

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2017-10-04
      • 2017-08-31
      • 1970-01-01
      • 2017-08-07
      相关资源
      最近更新 更多