springboot自定義屬性注入


創建一個springboot工程

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

如果是讀取application.properties或者是application.yml中的自定義屬性的話就不需要使用@PropertySource這個注解

@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 +
                '}';
    }
}

properties

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);
    }
}

控制台輸出

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

測試成功

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM