原生配置文件导入(xml)以及配置绑定
二、原生配置文件导入
@ImportResource
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="user01" class="com.atguigu.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="user02" class="com.atguigu.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
@ImportResource("classpath:beans.xml")
public class MyConfig {}
// =======测试======
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true
三、配置绑定
使用情况:
当组件的一些属性需要变动,或者不便于在代码中写死,此时可以将一些属性值写在配置文件中,便于修改。
1、@Component+@ConfigurationProperties
作用:将配置文件中配置的属性绑定到容器中的类中
属性:
prefix:配置文件中的前缀
tips:
只有在容器中的组件才能使用配置绑定,所以一般都会同时使用@Component直接
@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person{
private String name;
private Integer age;
}
2、@EnableConfigurationProperties+@ConfigurationProperties
@EnableConfigurationProperties:
作用:开启属性配置功能,同时将要开启属性配置功能的组件放入容器中
属性:
value:Class类型的,开启哪个类的属性配置功能
使用:
一般标注在配置类上
示例:
@@ConfigurationProperties(prefix = "user")
@Data
class User{
private String name;
private Integer age;
}
@EnableCongigurationProperties(USer.class)
//1、开启User配置绑定功能
//2、把USer这个组件自动注册到容器中
@Configuration
class MyConfig{
}