Spring Boot中的 @ConfigurationProperties

看各种框架的spring boot版本,配置信息都写在yml或properties文件里了,这里实际上用了@ConfigurationProperties注解,源代码的流程很复杂,先看看怎么使用.

方式1:注解加在类上

@Component
@ConfigurationProperties(prefix = "test")
public class TestConfiguration {
    private String name;
    private Integer age;

     ...........
}

配置文件: 

test.name=liming
test.age=25

测试: 

@RestController
@RequestMapping("/con")
public class Controller {

    @Autowired
    private TestConfiguration testConfiguration;

    @GetMapping("/test1")
    public String get(){
        return testConfiguration.toString();
    }
}

/test1结果:TestConfiguration{name='liming', age=25}

 

方式2:注解加在Bean上

public class TestConfiguration2 {
    private String name;
    private Integer age;
    ......
}

建一个配置类,在配置类里建个Bean,new个实体类

@Configuration
public class Confi {
 
    @Bean(name="TEST2") // 如果没有name,默认是类名TestConfiguration2 
    @ConfigurationProperties(prefix = "test")
    public TestConfiguration2 get2(){
        TestConfiguration2 testConfiguration2 = new TestConfiguration2();
        System.out.println(testConfiguration2.toString());
        return testConfiguration2;
    }
}

controller测试: 

    // 如果bean的name为默认,则用@autowired注入
    /*@Autowired
    private TestConfiguration2 testConfiguration2;*/


    @Resource(name="TEST2")
    private TestConfiguration2 testConfiguration2;

    @GetMapping("/test2")
    public String get2(){
        return testConfiguration2.toString();
    }

项目启动发现,spring 加载bean,bean的打印结果为:TestConfiguration{name='null', age=null}

说明加载bean比从Properties里拿值要快,

访问/test2已经有值了 :TestConfiguration{name='liming', age=25}

 

扩展:与@Qualifier 组合运用

Properties文件里添加test_前缀

test_.name=Tom
test_.age=27

让TEST3对象作为参数传给TEST4里.

    @Bean(name = "TEST3")
    @ConfigurationProperties(prefix = "test_")
    public TestConfiguration2 get3(){

        TestConfiguration2 testConfiguration2 = new TestConfiguration2();
        System.out.println(testConfiguration2.toString());
        return testConfiguration2;
    }


    @Bean(name = "TEST4")
    public String test(@Qualifier("TEST3") TestConfiguration2 testConfiguration2){

        return testConfiguration2.toString();
    }

controller测试:

    @Resource(name="TEST4")
    private String TEST4str;
    @GetMapping("/test3")
    public String get3(){
       return TEST4str;
    }

访问结果:TestConfiguration{name='Tom', age=27}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值