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

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

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


            org.springframework.boot
            spring-boot-configuration-processor
            true
        
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进来,至此大功告成

@Autowired
private LoginTypeProperties loginTypeProperties;

你可能感兴趣的:(springboot)