Springboot中@ConfigurationProperties轻松管理应用程序的配置信息

2023-12-25 13:07:18

🍁 作者:知识浅谈,CSDN签约讲师,CSDN博客专家,华为云云享专家,阿里云专家博主
📌 擅长领域:全栈工程师、爬虫、ACM算法
💒 公众号:知识浅谈
🔥网站:vip.zsqt.cc

🤞ConfigurationProperties轻松管理应用程序的配置信息🤞

🎈@ConfigurationProperties是什么

@ConfigurationProperties 注解的作用是将外部配置文件中的属性值注入到一个 Java Bean 中。这样做的好处是可以方便地将配置文件中的属性值与 Java Bean 对象进行绑定,使得配置属性的读取和管理更加方便。

通过 @ConfigurationProperties 注解,我们可以在 Spring Boot 应用程序中轻松地将配置文件中的属性值映射到一个 POJO(Plain Old Java Object)类中,从而实现类型安全的属性访问。这样一来,我们无需手动编写代码来读取配置文件中的属性,而是可以直接将配置文件中的属性值注入到一个预定义的 Java Bean 对象中,然后在代码中直接使用这些属性值。

🎈案例实现

假设有一个 application.properties 文件包含以下属性:

myapp.user.name=John
myapp.user.age=30

我们可以创建一个 UserProperties 类,并使用 @ConfigurationProperties 注解将这些属性值映射到该类中:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "myapp.user")
public class UserProperties {
    private String name;
    private int age;
}

然后,我们可以在代码中直接注入 UserProperties 对象,并访问其中的属性值:

@Service
public class UserService {
    private final UserProperties userProperties;

    public UserService(UserProperties userProperties) {
        this.userProperties = userProperties;
    }

    public void displayUserInfo() {
        System.out.println("User Name: " + userProperties.getName());
        System.out.println("User Age: " + userProperties.getAge());
    }
}

通过使用 @ConfigurationProperties 注解,我们可以很方便地将外部配置文件中的属性值注入到 UserProperties 对象中,而不需要在代码中硬编码这些属性值,这样做可以提高代码的可维护性和灵活性。

🍚总结

大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。
Writted By 知识浅谈

文章来源:https://blog.csdn.net/qq_37699336/article/details/135195596
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。