SpringBoot @PropertySource与@ImportResource有什么区别

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot @PropertySource与@ImportResource有什么区别

zoeil   2023-02-03 我要评论

前言

在SpringBoot中,对于JavaBean的属性一般都绑定在配置文件中,比如application.properties/application.yml/application.yaml,这三个配置文件前面的优先级高于后面的,即对于同名属性,前面的配置会覆盖后面的配置文件。

当我们自己创建类,也想放到容器中,可以单独建立文件,可以通过@PropertySource与@ImportResource这两个注解来注入到Servlet容器中,就可以搞定不在主配置里读取,按照不同的功能模块划分出不同的配置文件。

前者适合yml、yaml格式,而@importResource则适用于xml文件格式,如beans.xml 可以把其注解到窗口中,不过要放在spring boot主配置文件头部

@PropertySource

可以自定义配置文件名称,不在默认配置文件中读取值,多用于额外配置文件与实体属性映射。

在从配置文件里获取值,与JavaBean做映射。存在一个问题,我们是从主配置(application.yml)里读取的。如果全部的配置都写到application里,那么主配置就会显得特别臃肿。为了按照不同模块自定义不同的配置文件引入了@PropertySource

user.name=张三
user.age=24
user.email=xxxxxxx@qq.com
user.address=xx省xx市xx区

JavaBean

@Data
@PropertySource(value = {"classpath:user.properties"})
@ConfigurationProperties(prefix = "user")
@Component
public class Person {
    private String name;
    private Integer age;
    private String email;
    private String address;
}

这样一个注解(@PropertySource(value = {“classpath:person.properties”}))就可以搞定不在主配置里读取,按照不同的功能模块划分出不同的配置文件。

@ImportResource

一般情况下我们自定义的xml配置文件,默认情况下这个bean是不会加载到Spring容器中来的。需要@ImportResource注解将这个配置文件加载进来。

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="UserService" class="com.boot.UserService"></bean>
<beans>

JavaBean

public class UserService {
}

修改启动类

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class Springboot02ConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot02ConfigApplication.class, args);
    }
}

小结

@PropertySource 用于引入*.Properties或者 .yml 用于给javabean注入值

一般用在javabean的类名上

@ImportResource 用于引入.xml 类型的配置文件 在spring boot中已经被配置类(@Bean)替代 一般用于启动类上

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们