SpringBoot2.0---------------4、SpringBoot底层注解之原生配置文件引入

@ImportResource注解


@ImportResource注解用于导入Spring的xml配置文件,传统的Spring项目包含大量的xml配置,若将重写为配置类是非常麻烦的事情,因此通过@ImportResource让该配置文件中定义的bean对象加载到Spring容器中。之所以使用该注解是因为在Springboot环境中无法识别Spring的xml配置文件,从而无法将配置文件中的对象加载到容器中。

举个例子,Spring的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="haha" class="com.lyy.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>
    <bean id="hehe" class="com.lyy.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

在某个配置类中使用@ImportResource注解,并将资源路径进行指定—》@ImportResource(“classpath:beans.xml”)

@Import({User.class, DBHelper.class})
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
@Configuration(proxyBeanMethods = true) //告诉springboot这是一个配置类==配置文件
@ImportResource("classpath:beans.xml")
public class Myconfig {

    /*
    * 外部对配置类中的这个组件注册方法调用多少次,获取的都是之前注册容器中的单实例对象
    * */

    @Bean //给容器中添加组件。以方法名作为组件的id,返回类型就是组件类型;返回的值,就是组件在容器中保存的实例
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        zhangsan.setPet(Tomcat());
        return zhangsan;
    }
    @Bean("tom22")
    public Pet Tomcat(){
        return new Pet("luopeixi");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值