@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");
}
}