Spring Boot (三) 将配置自动封装到实体

1. 背景与结论

  • 背景:很多时候我们需要将配置文件中的值取出来,封装为一个实体再进行使用,如果能自动帮我们封装好,那就省去了我们手动封装的麻烦了,大大节省了时间。
  • 结论:我们可以使用Spring Boot中的@ConfigurationProperties注解来实现这个功能

2. 实现

下面我们就来具体实现一下吧。

2.1配置文件

application.properties

test.properties.userName=Admin
test.properties.email=test@test.com
test.properties.age=18
test.properties.url=http://localhost:8060/test/properties
2.2 封装配置信息实体编写

TestProperties.java

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

@Component
@ConfigurationProperties(prefix = "test.properties")
public class TestProperties {
   private String userName;

   private String email;

   private Integer age;

   private String url;

   public String getUserName() {
       return userName;
   }

   public void setUserName(String userName) {
       this.userName = userName;
   }

   public String getEmail() {
       return email;
   }

   public void setEmail(String email) {
       this.email = email;
   }

   public Integer getAge() {
       return age;
   }

   public void setAge(Integer age) {
       this.age = age;
   }

   public String getUrl() {
       return url;
   }

   public void setUrl(String url) {
       this.url = url;
   }

   @Override
   public String toString() {
       return "TestProperties{" +
               "userName='" + userName + '\'' +
               ", email='" + email + '\'' +
               ", age=" + age +
               ", url='" + url + '\'' +
               '}';
   }
}
  • properties文件中key除去prefix.后一定要和封装对象的field保持一致
  • 在@ConfigurationProperties注解中配值需要自动封装的配置信息的前缀,@Component标识这个实体是一个组件,交由Spring容器管理,在使用的时候可以直接注入进来
2.3 编写Controller

TestController.java

import cn.sweetz.exercise.springbootdemo.property.TestProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/test")
public class TestController {
    
    @Resource
    private TestProperties testProperties;
    
    @GetMapping("/properties")
    public String getTestProperties(){
        return testProperties.toString();
    }
}

3. 运行与测试

启动项目,等到项目启动好了后,输入地址:http://localhost:8060/test/properties运行结果图
我们配置的一些信息已经自动帮我们封装到TestProperties实体中了,真的是很方便啊!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值