底层注解-@ImportResource导入Spring配置文件

比如,公司使用bean.xml文件生成配置bean,然而你为了省事,想继续复用bean.xml,@ImportResource粉墨登场。

一、简单演示

bean.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans ...">

    <bean id="haha" class="com.lun.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.lun.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

使用方法:

@configuration
@ImportResource("classpath:beans.xml")
public class MyConfig {
...
}

测试类:

public static void main(String[] args) {
    //1、返回我们IOC容器
    ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

	boolean haha = run.containsBean("haha");
	boolean hehe = run.containsBean("hehe");
	System.out.println("haha:"+haha);//true
	System.out.println("hehe:"+hehe);//true
}

二、详细解释

@ImportResource是一个Spring注解,用于在Java配置类中导入XML配置文件。通过使用@ImportResource注解,你可以将XML配置文件中定义的bean和配置引入到你的应用程序中。

以下是使用@ImportResource注解导入Spring配置文件的示例:

  1. 创建一个XML配置文件,比如applicationContext.xml,其中包含你的bean定义和其他配置。
<!-- applicationContext.xml -->
<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 https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="exampleBean" class="com.example.ExampleBean">
        <!-- bean配置 -->
    </bean>

</beans>

        2. 在你的Java配置类中使用@ImportResource注解导入XML配置文件。

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

@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
    // 配置类代码
}

在上面的示例中,我在AppConfig配置类上使用了@ImportResource注解,并指定了需要导入的XML配置文件的类路径(classpath)。

这样,当你的应用程序启动时,XML配置文件中定义的bean和配置将被加载和应用。

需要注意的是,推荐尽量使用基于Java的配置方式(例如使用@Configuration@Bean注解)来代替XML配置文件,以获得更好的类型安全和编译时检查。只有在必要的情况下,使用@ImportResource注解来导入XML配置文件。

猜你喜欢

转载自blog.csdn.net/weixin_55772633/article/details/131868910