@ImportResource和@PropertySource以及@ConfigurationPropertites的区别

目录

@ImportResource

 @PropertySource

 @ConfigurationProperties


@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注解一起使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值