我们通常会把一些经常变动的东西放到配置文件里。
比如之前写在配置文件application.properties里的端口号server.port=8080,另外常见的还有数据库的连接信息等等。
那么,我的数据库连接信息放在配置文件里,我要使用的话肯定得去解析配置文件,解析出的内容在 bean 里面去使用。
整个场景其实就是把配置文件里的所有配置,绑定到 java bean 里面。
要完成这个场景,基于 java 原生代码编写还是有点麻烦的。通常会做一个封装,读取到properties文件中的内容,并且把它封装到javabean中:
public class getproperties { public static void main(string[] args) throws filenotfoundexception, ioexception { properties pps = new properties(); pps.load(new fileinputstream(a.properties)); enumeration enum1 = pps.propertynames();//得到配置文件的名字 while(enum1.hasmoreelements()) { string strkey = (string) enum1.nextelement(); string strvalue = pps.getproperty(strkey); system.out.println(strkey + = + strvalue); //封装到javabean ... ... } }
这里就是使用properties类来加载配置文件a.properties,然后遍历配置文件中的每一个k-v,获取之后就可以用到对应的地方。
在 springboot 中简化了这个过程,这就是配置绑定。
配置绑定通过使用注解@configurationproperties来完成配置绑定,注意需要结合@component使用。
新建一个组件car,有2个属性分别是品牌和价格:
@componentpublic class car { private string brand; private integer price;// get set tostring 就不贴了
在配置文件application.properties,设置一些属性值,比如:
mycar.brand=qqmycar.price=9999
使用@configurationproperties注解,加到组件上:
@component@configurationproperties(prefix = mycar)public class car { private string brand; private integer price;... ...
传进去的 prefix 是配置文件里的前缀,这里就是 mycar。
验证现在来测试一下是否绑定成功,在之前的hellocontroller继续增加一个控制器方法:
@restcontrollerpublic class hellocontroller { @autowired car car; @requestmapping(/car) public car car() { return car; } @requestmapping(/hello) public string hello() { return hello springboot2 你好; }}
部署一下应用,浏览器访问http://localhost:8080/car:
绑定成功。
另一种方式除上述方法之外,还可以使用@enableconfigurationproperties + @configurationproperties的方式来完成绑定。
注意,@enableconfigurationproperties注解要使用在配置类上,表示开启属性配置的功能:
//@conditionalonbean(name = pet1)@import({user.class, dbhelper.class})@configuration(proxybeanmethods = true)@importresource(classpath:beans.xml) //配置文件的类路径@enableconfigurationproperties(car.class) //开启属性配置的功能public class myconfig { @bean(user1) public user user01(){ user pingguo = new user(pingguo,20); pingguo.setpet(tomcatpet()); return pingguo; } @bean(pet22) public pet tomcatpet(){ return new pet(tomcat); }}
@enableconfigurationproperties(car.class)传入要开启配置的类,这可以自动的把 car 注册到容器中,也就是说之前 car 上的@component就不需要了。
//@component@configurationproperties(prefix = mycar)public class car { private string brand; private integer price;
重新部署访问下地址,依然可以。
关于第二种的使用场景,比如这里的 car 是一个第三方包里的类,但是人家源码没有加@component注解,这时候就可以用这种方式进行绑定。
最后,要记住当使用@configurationproperties(prefix = mycar)这个配置绑定时,是跟 springboot 核心配置文件 application.properties文件的内容建立的绑定关系。
以上就是springboot2底层注解@configurationproperties如何配置绑定的详细内容。