springboot自定義屬性注入

建立一個springboot工程spring

編寫實體類 讀取自定義配置文件中的自定義屬性springboot

若是是讀取application.properties或者是application.yml中的自定義屬性的話就不須要使用@PropertySource這個註解app

@Component
@ConfigurationProperties(prefix = "lyf")
@PropertySource(value = "classpath:lyf.properties")
public class LyfBean {
    private String name;
    private Integer age;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "LyfBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

propertieside

lyf.name:liuyifeng
lyf.age:20

編寫測試類測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestEnv {
    @Autowired
    private LyfBean bean;
    @Test
    public void test(){
        System.out.println(bean);
    }
}

控制檯輸出this

LyfBean{name='liuyifeng', age=20}

測試成功spa

相關文章
相關標籤/搜索