底层注解-@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配置文件。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值