项目中我们总避免不了使用properties
文件定义一些配置属性,然后将这些配置注入到对应属性上让其生效,那么Spring
中和Spring Boot
对properties处理有什么差别呢?那就一起来看看。
注意:
本文创建一个简单的SpringBoot项目,分别使用两种方式来演示
1. Spring中properties属性注入
1.1 配置属性值到application.properties中
1.1.1 创建实体类User.java
public class User {
private Integer id;
private String name;
private String address;
//省略getter和setter方法
}
1.1.2 将属性值配置在application.properties
# application.properties配置文件会在项目启动时就加载到Spring容器
user.id=1
user.name=wanik
user.address=beijing
1.1.3 注入属性到User
@Component //将该bean添加到Spring容器中
public class User {
//application.properties配置文件会在项目启动时就加载到Spring容器
//这里我们可以直接使用@Value("${key}")注解将properties中的值注入到指定属性
@Value("${user.id}")
private Integer id;
@Value("${user.name}")
private String name;
@Value("${user.address}")
private String address;
//省略getter/setter方法,必须存在setter方法
}
1.1.4 测试
//SpringBoot测试类
@SpringBootTest
class PropertiesApplicationTests {
//注入User对象到测试类
@Autowired
User user;
@Test
void test1(){
System.out.println(user);
}
}
打印结果:
1.2 定义外部配置文件user.properties
在外部自定义properties文件也是我们常用的一种方式,比如db.properties等,那么这个文件在项目启动时不会被自动加载到Spring容器中,那么我们就要通过修改上述要注入的User实现。
通过@PropertySource(path)注解指定properties文件路径
@Component //将该bean添加到Spring容器中
@PropertySource("classpath:user.properties") //指定properties文件路径
public class User {
//application.properties配置文件会在项目启动时就加载到Spring容器
//这里我们可以直接使用@Value("${key}")注解将properties中的值注入到指定属性
@Value("${user.id}")
private Integer id;
@Value("${user.name}")
private String name;
@Value("${user.address}")
private String address;
//省略getter、setter方法
}
测试:
第二种方式测试成功
上述介绍两种在Spring中注入properties方式,这两种方式同样在SpringBoot中适用,下面介绍Spring Boot中提供的另一种方式
2. Spring Boot中properties属性注入
Spring Boot提供了一种属性安全的注入方式,在属性值较多时这种方式非常简便,省略掉在每个属性上一对一通过@Value进行注入:
同样修改上述User类,如下:
@Component //将该bean添加到Spring容器中
@PropertySource("classpath:user.properties")
@ConfigurationProperties(prefix = "user")
public class User {
//@Value("${user.id}")
private Integer id;
//@Value("${user.name}")
private String name;
//@Value("${user.address}")
private String address;
//省略getter/setter方法
}