很多时候我们不知在默认的配置文件中存放过于的数据,这样回导致默认的配置文件数据冗余,可能会出现一些不必要的bug。但是用@value和@ConfigurationProperties只能从默认的配置文件获取数据,今天我们介绍的这两个组件将从我们指定的配置文件获取数据。
沿用之前的测试程序
user类
package com.example.springdemo.entity;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.util.List;
@Component//把User加到容器中
@Data
//@ConfigurationProperties(prefix = "com")
/**
* @ConfigurationProperties
* 可以将配置文件中的每一个属性的值,映射到这个组件中
* 告诉springboot将奔雷中的所有属性和配置文件中的相关属性先绑定
* prefix = "com"绑定配置文件com层级下的属性进行一一映射
* 只有是容器才能使用所以要添加注解@Component
*/
//@Validated
@PropertySource("classpath:user.properties")//指定配置文件
public class User {
/**
* <bean class="User">
* <prrperty name="name" value="我们赋的值"></prrperty>
* </bean>
*/
//@Value("#{11+9}")
private Long id;
//@Value("${User.name}")
private String name;
private Integer age;
private List<Object>list;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge(int i) {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String email;
public Integer getAge() {
return age;
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
}
我新增一个配置文件user.peoperties
我们保留之前的默认配置文件 也不删除
查看结果
我们发现这次封装实体类不会用默认的配置文件注册信息,
而是用我们指定的配置文件注册信息。
2.@ImportResource:
导入springboot的配置文件,让配置文件里面的内容生效
springboot里面没有spring的配置文件,我们自己编写的配置文件也不能自动识别;
我们添加一个bean.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.example.springdemo.service.HelloService"></bean>
</beans>
新建一个类
package com.example.springdemo.service;
public class HelloService {
}
测试结果
容器中是没有bean的配置信息的
我们在主类加上
@ImportResource(locations = {"classpath:beans.xml"})并且给上内路径
我们在测试结果发现这个时候beans已经封装到容器中了
但是springboot更支持用注解配置的的方式给容器添加组件。就是我们之前讲的大家