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工程中,这避免了将原生配置文件中的内容一个一个的用注解的形式的编写代码。