目录
@ImportResource
通常用于导入我们自定义的xml类型的配置文件,一般用于启动类中。一般的,xml文件中的bean是不会自动加载到spring容器中,此时需要我们手动导入。
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:http://localhost:3306/kgcnews?useSSL=false&characterEncoding=utf-8&serverTimeZone=GMT
jdbc.username=root
jdbc.password=root
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"
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
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSrouce" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="classpath*:jdbc.properties"/>
</beans>
启动
@SpringBootApplication
@ImportResource(value = "classpath:bean.xml")
public class Demo04JdbcApplication {
public static void main(String[] args) {
SpringApplication.run(Demo04JdbcApplication.class, args);
}
}
@PropertySource
用于自定义配置文件与实体属性之间的映射,一般结合@ConfigurationProperties注解标记配置文件中实体属性的前缀。最终将配置文件中配置的实体类属性值对应带相应实体类中,并通过@Component注解注入到spring容器中。
person.properties
person.name=法外狂徒
person.age=22
person.sex=男
person.birth=1999/11/11
person.boss=张三
person.maps.key1=value1
person.map2.key2=value2
person.law.level=first
person.law.year=10
Person.class
@PropertySource(value = "classpath:person.properties")
@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person {
private String name;
private Integer age;
private String sex;
private Date birth;
private String boss;
private Map<String ,String> maps;
private Law law;
}
@ConfigurationProperties
如果指定了自定义配置文件的路径,则ConfigurationProperties注解会在指定的配件文件中通过指定的前缀值去查找实体类锁依赖的属性值。若没有指定,application.properties文件中查找。该注解得配合@Component注解才能将实体对象注入到spring容器中。
总结:
@ImportResource主要用于导入.xml类型的配置文件
@PropertySource用于导入自定义的.properties文件或者.yml文件
@ConfigurationProperties用户指定实体类属性值在配置文件中的前缀标记,一般结合@Component注解一起使用