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