浑浑噩噩做了两年的Android,最近开始进军Java服务器后端开发。所以有机会学习了SpringBoot框架,只能说SpringBoot框架的注入正式太牛逼了,不过需要记得东西也不少,先慢慢做笔记吧,相信自己会一步一步的做好的。
今天主要记录一下application.properties中属性值的加载,一共有两种种方式,我逐一介绍。首先我们先做一些准备工作。
在resource文件夹中创建application.properties文件,并添加如下测试内容
test.name=gzc
test.pwd=a123123
test.age=26
一、使用@Bean注解及构造方法方式实现
1、创建TestProperties.java文件,@Data注解是lomok的三方库,主要是用来生成set、get等方法
@ConfigurationProperties(prefix = "test")
@Data
public class TestProperties {
String name;
String pwd;
int age;
}
@ConfigurationProperties这个注解从字面意思就可以知道,作用是加载配置文件,括号中的“test”对应application.properties中的“test”,意义一眼明了
2、创建TestBean.java文件
@Configuration
@EnableConfigurationProperties(TestProperties.class)
@Data
public class TestBean {
String name;
String pwd;
int age;
@Bean
public TestBean init(TestProperties testProperties){
this.name = testProperties.getName();
this.pwd = testProperties.getPwd();
this.age = testProperties.getAge();
return this;
}
}
@Configuration这个注解我理解的不是好,应该是一种标记,来被SpringBoot扫描,扫到后进入类内部继续扫描,扫到@Bean注解后构建Bean(如有不对请指出)
@EnableConfigurationProperties这个注解就很好理解了,去加载括号中的文件,这里是TestProperties.class,上面也说过,TestProperties这个文件主要是加载配置文件,这里主要就是从这个类对象中拿到配置文件里的属性
我们在SpringtestApplicationTests测试类中测试输出一下
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringtestApplicationTests {
@Autowired private TestBean testBean;
@Test
public void contextLoads() {
System.out.println(testBean.toString());
}
}
输出:
TestBean(name=gzc, pwd=a123123, age=26)
3.我们对TestBean进行简单的改造,在构造方法中添加TestProperties类
@Configuration
@EnableConfigurationProperties(TestProperties.class)
@Data
public class TestBean {
String name;
String pwd;
int age;
public TestBean(TestProperties testProperties) {
this.name = testProperties.getName();
this.pwd = testProperties.getPwd();
this.age = testProperties.getAge();
}
}
我们进行输出测试,依然是成功的
二、方法中使用@Configuration的方式
这种方法非常的优雅,我们删掉TestProperties文件,对TestBean文件做如下的改造,TestBean变成了一个普通的Bean类
@Data
public class TestBean {
String name;
String pwd;
int age;
}
添加TestConfigure文件
@Configuration
public class TestConfigure {
@Bean
@ConfigurationProperties(prefix = "test")
public TestBean init(){
return new TestBean();
}
}
我们只需要把ConfigurationProperties注解添加到相应的方法即可
我们先写一下测试代码
@Configuration
public class TestConfigure {
@Bean
@ConfigurationProperties(prefix = "test")
public TestBean init(){
return new TestBean();
}
}
输出如下:
TestBean(name=gzc, pwd=a123123, age=26)
这是什么鬼,为何会如此神奇!?一句代码就秒杀了方法一中那么啰嗦的方法。当然这个实现是有一个前提的,那就是TestBean这个类中的属性名要和application.properties方法中的属性名称相等。
虽然方法二中的方式比方法一更优雅,但是各自使用的场景并不一样。只能说各有优缺点吧