springboot实现将配置文件的属性转换成一个对应的pojo对象的属性

来源:互联网 发布:杨辉三角形的规律c语言 编辑:程序博客网 时间:2024/05/20 18:19

1.首先你需要在application.yml(如果是application.properties也差不多)配置文件配置相应的属性信息,例如

loginType:  person: 1  vcode: 23
2.在pom文件加入下面的依赖

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-configuration-processor</artifactId>            <optional>true</optional>        </dependency>
3.写一个相应的pojo类,注意prefix后面的需要写你自己的

@ConfigurationProperties(prefix = "myProperties.loginType")

package com.suiyu.account.properties;import org.springframework.boot.context.properties.ConfigurationProperties;/** * @author yedeguo * @date 2017/8/24 */@ConfigurationProperties(prefix = "loginType")public class LoginTypeProperties  {    private String person;    private String vcode;    public String getPerson() {        return person;    }    public void setPerson(String person) {        this.person = person;    }    public String getVcode() {        return vcode;    }    public void setVcode(String vcode) {        this.vcode = vcode;    }    public LoginTypeProperties() {    }    public LoginTypeProperties(String person, String vcode) {        this.person = person;        this.vcode = vcode;    }    @Override    public String toString() {        return "LoginTypeProperties{" +                "person='" + person + '\'' +                ", vcode='" + vcode + '\'' +                '}';    }}

4.在springboot的入口main方法加上下面的这个注解,括号里面的写你自己的pojo类@EnableConfigurationProperties(LoginTypeProperties.class)

@SpringBootApplication@EnableConfigurationProperties(LoginTypeProperties.class)public class AccountApplication {    public static void main(String[] args) {        SpringApplication.run(AccountApplication.class, args);    }}
5.然后就可以在相应的Controller层或者其他地方@Autowired进来,至此大功告成

@Autowiredprivate LoginTypeProperties loginTypeProperties;

阅读全文
0 0
原创粉丝点击