springboot配置文件:
@ConfigurationProperties:从配置文件中获取值
@Value:从配置文件中获取值
@PropertySource:加载指定的配置文件
@Import: 加载类
@ImportResource: 加载.xml
@ConfigurationProperties(扫描整个配置文件-)
- 与@Bean结合为属性赋值
- 与***[@PropertySource(只能用于properties文件)]***结合读取指定文件
- 与@Validation结合,支持JSR303进行配置文件值的校验,如@NotNull@Email等
@Value(可以是普通字符串 / 操作系统属性/ 表达式/ 配置属性)
- 为单个属性赋值
- 支持属性上的SpEL表达式
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定 | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 |
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
@Email
//@Value("${person.last-name}")
private String lastName;
//@Value("#{11*3}")
private Integer age;
.yml配置文件
person:
lastName: hello
age: 19
boss: false
birth: 2019/11/12
maplist:
- name: abc
value: abcValue,abc
- name: 123
value: [123Value,123]
@PropertySource:加载指定的配置文件
@PropertySource(value = {"classpath:student.properties"})
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private Integer id;
private String username;
private Integer age;
student.properties配置文件
student.id=30
student.username=王五
student.age=33
student.boss=true
student.birth=2018/03/03
student.lists=lisa,wangwu3
student.maps.k1=300
student.maps.k2=300
student.dog.name=小狗3
student.dog.age=3
@Import:导入java类
public class Cat {
@Value("cat")
private String name;
@Value("3")
private Integer age;
}
public class Pig {
@Value("pig")
private String name;
private Integer age;
}
@SpringBootApplication
@Import({Pig.class, Cat.class})
public class Springboot01Application {
public static void main(String[] args) {
SpringApplication.run(Springboot01Application.class, args);
}
@ImportResource 是导入spring配置的.xml文件
beans.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="dogxml" class="com.panshi.springboot01.pojo.Dog">
<property name="name" value="jack"></property>
<property name="age" value="18"></property>
</bean>
</beans>
item.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="itemService" class="com.panshi.springboot01.service.ItemService"></bean>
</beans>
@ImportResource(locations = {"classpath:beans.xml","classpath:item.xml"})
@SpringBootApplication
public class Springboot01Application {
public static void main(String[] args) {
SpringApplication.run(Springboot01Application.class, args);
}
}
下面这种方式也可以注入属性
@Configuration
public class MyConfig {
// 将方法的返回值添加到容器中,容器中这个组件的id默认为方法名
@Bean
public ItemService itemService() {
return new ItemService();
}
}