SpringBoot注解讲解(@ImportResource)

1、@ImportResource的作用

该注解主要用于原生配置文件引入。SpringBoot是全注解开发,对于一些使用配置文件项目,SpringBoot可以通过@ImportResource将配置文件中的内容引入SpringBoot项目中,不需要将配置文件中的内容一个一个的按照注解的方式改动。

2、@ImportResource的使用

在我们的工程中创建一个xml文件,使用xml文件向容器装配组件。在SpringBoot工程中,可以使用@ImportResource将xml文件中的内容装入容器中。

(1)创建常规Spring工程中的xml文件,该文件向IOC容器中装入两个组件,分别名为haha和hehe。

<?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="haha" class="com.yjh.bean.User">
        <property name="name" value="haha"/>
        <property name="age" value="18"/>
    </bean>

    <bean id="hehe" class="com.yjh.bean.Pet">
        <property name="name" value="hehe"/>
    </bean>

</beans>

(2)在配置类上使用@ImportResource将原生配置文件bean.xml文件引入,关键代码:@ImportResource("classpath:bean.xml)

@Import({User.class})
@Configuration(proxyBeanMethods = true)
@ConditionalOnMissingBean(name="tom")
@ImportResource("classpath:bean.xml")
public class MyConfig {
    @Bean
    public User user01()
    {
        User zhangSan = new User("张三",18);
        zhangSan.setPet(pet01());
        return zhangSan;
    }

    @Bean
    public Pet pet01()
    {
        return new Pet("tomcat");
    }
}

(3)在主程序中输出所有的组件名字,验证@ImportResource已经将原生xml文件中的组件装配到容器中。

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
        String[] beanDefinitionNames = run.getBeanDefinitionNames();
        for(String beanName:beanDefinitionNames)
        {
            System.out.println(beanName);
        }

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

输出结果:

表明xml文件中的组件已经装配到容器中了。

3、总结

 注解@ImportResource能够将原生配置文件引入SpringBoot工程中,这避免了将原生配置文件中的内容一个一个的用注解的形式的编写代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值