Spring注解之@ImportResource和@PropertySource分析

本文介绍如何在Spring Boot中使用@ImportResource注解引入XML配置文件,并通过@PropertySource注解加载属性文件进行属性注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:写在前面

之前我们使用spring,最多的还是通过xml配置文件的方式来配置spring bean等内容,随着注解的广泛应用和spring4中Java config的引入,xml配置文件方式逐步被替换,但是如果是想要使用xml配置文件方式的话,也可以通过@ImportResource注解来实现,下面我们来一起看下如何使用。
本文基于springboot来进行测试,对springboot不了解或者是想要直接获取测试代码的朋友,可以参考这篇文章

2:ImportResource

2.1:定义包和类

首先定义一个不会被ComponentScan扫描到的包outpackage,如下:
在这里插入图片描述
在该包内创建一个类:

package outpackage;

import org.springframework.stereotype.Service;

@Service
public class HelloService1 {
    public void method1() {
        System.out.println("class:HelloService1__method:method1");
    }
}

2.2:定义配置文件

在资源目录添加配置文件applicationContext.xml

<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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 开启注解模式 -->
    <context:annotation-config/>

    <!-- 基于注解自动注册spring bean -->
    <context:component-scan base-package="outpackage"/>
</beans>

2.3:定义Java Config类

在启动类平级目录或者是子目录添加java config类保证能够被springboot扫描到,引入xml配置,如下:

package dongshi.daddy;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource({"classpath:applicationContext.xml"})
public class OuterPackageConfiguration {
}

2.4:测试代码

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws URISyntaxException, IOException {
        ConfigurableApplicationContext run = SpringApplication.run(HelloWorldMainApplication.class, args);
        // 获取通过配置文件定义而被扫描到的类
        HelloService1 bean = run.getBean(HelloService1.class);
        System.out.println(bean);
    }
}

运行:

2021-05-19 17:52:52.896  INFO 16232 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8083 (http) with context path ''
...snip...
outpackage.HelloService1@1929425f

为了证明确实是xml配置文件在起作用,而不是springboot自己扫描注册,修改配置类,注释掉@ImportResource({"classpath:applicationContext.xml"}),如下:

package dongshi.daddy;

import org.springframework.context.annotation.Configuration;

@Configuration
//@ImportResource({"classpath:applicationContext.xml"})
public class OuterPackageConfiguration {
}

然后运行:

2021-05-19 18:01:10.522  INFO 18260 --- [           main] dongshi.daddy.HelloWorldMainApplication  : Started HelloWorldMainApplication in 0.944 seconds (JVM running for 1.355)
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'outpackage.HelloService1' available
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
	at dongshi.daddy.HelloWorldMainApplication.main(HelloWorldMainApplication.java:16)

可以看到就找不到对应的bean了。

3:PropertySource

该注解的作用和ImportResource作用类似,都是用来引入文件的,只不过ImportResource用来引入xml的配置文件,而PropertySource注解用来引入properties的属性文件,一般注入属性值使用。

3.1:定义测试bean

@Component("myBean")
@PropertySource("classpath:myPropertySourceBean.properties")
public class MyPropertySourceBean {
    @Value("${myBean.name}")
    private String name;
    @Value("${myBean.age}")
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "MyPropertySourceBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.2:定义属性文件

myPropertySourceBean.properties:

myBean.name=jack
myBean.age=90

3.3:测试

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws URISyntaxException, IOException {
        ConfigurableApplicationContext run = SpringApplication.run(HelloWorldMainApplication.class, args);
        MyPropertySourceBean bean = run.getBean(MyPropertySourceBean.class);
        System.out.println(bean);
    }
}

运行:

......
MyPropertySourceBean{name='jack', age=90}

注意到在bean中还需要配合@Value注解和SpEL来注入值,针对这点springboot引入了@ConfigurationProperties注解来自动注入属性值,优化如下:

@Component("myBean")
@PropertySource("classpath:myPropertySourceBean.properties")
@ConfigurationProperties(prefix = "mybean")
public class MyPropertySourceBean {
//    @Value("${myBean.name}")
    private String name;
//    @Value("${myBean.age}")
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "MyPropertySourceBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

增加了@ConfigurationProperties(prefix = "mybean"),删除了@Value相关注解,运行效果不变,大家可以试下。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值