java - @ConfigurationProperties在spring中的使用

标签 java spring spring-boot spring-mvc

我有一个基于 struts 框架构建的项目,但我已将 Spring Framework 集成到同一项目中(使用 servlet-config.xml)并使用 其中包含 MVCAOP,现在在一项要求中,我必须使用一个基于 SpringBoot 构建并使用 @ConfigurationProperties 的项目将 application.yml 文件与 POJO 绑定(bind)。

我只需要使用该项目的代码,因此添加了该项目的依赖项。有什么方法可以使用 @ConfigurationProperties 来将 POJO 与项目中的 yml 文件绑定(bind)。我尝试过,但 bean 未与 yml 文件条目绑定(bind)。

据我所知,@ConfigurationProperties 仅是 SpringBoot 功能的一部分。

请提出您有用的建议。

最佳答案

您可以执行如下所示的操作:

如果您的 yml 文件具有包含相同前缀的属性,那么您可以使用如下内容:

POJO 类:

@Configuration // add this if your spring boot version is < 2.2 or else please donot add.
@ConfigurationProperties(prefix = "spring.db.props") //example
public class MyPojoProps{ 

    private String userName; 
    private int password; 
    private String uri; 

    // standard getters and setters 
}

您的 application.yml 可能如下所示:

application.yml

spring:
  db:
   props:
     userName:
     password:
     uri:

Please refer here for more information

关于java - @ConfigurationProperties在spring中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60397755/

相关文章:

java - 如何使用spring的MockMultipartHttpServletRequest?获取 "no multipart boundary was found"

java - 追加字节

java - 如何在 JavaFX 中正确显示这个特定的形状路径?

spring - 无法在 Spring REST Controller 中将 Map 用作 JSON @RequestParam

java - 当自定义事务管理器连接失败时,Spring Boot应用程序不会快速失败

java - SpringUI 无法解析为类型

java - 尝试使用maven程序集插件时出现 "Assembly is incorrectly configured: null"

java - 如何检查字符串中的逻辑运算符或将字符串转换为Java中的代码

spring - 使用 Spring Security 和 CAS 进行单点注销

Eclipse:为 spring bean 和上下文打开声明/资源