我们都知道Spring是基于XML配置的,而Spingboot是在Spring的基础上进行改进的,它默认是不支持XML配置的,在Springboot上无法识别XML配置文件。
那我们想在Springboot中使用XML配置该如何进行,这时候就需要 @ImportResource注解了。
接下来我们通过一个案例来演示@ImportResource注解的使用:
- 先创建一个Cat类
/**
* 创建一个实体类,Springboot默认是不支持XML配置文件的,那如果我们需要使用xml配置文件的话,那需要使用@ImportResource注解
*/
public class Cat {
}
- 然后我们在resource中创建一个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="cat" class="com.xuejia.springboot10.POJO.Cat"></bean>
</beans>
- 这时候想要Springboot识别并加载这个XML配置文件,就需要@ImportResource注解了。@ImportResouce注解需要加在当前Springboot框架的主配置类上。
@SpringBootApplication
@ImportResource("classpath:Bean.xml")//在主配置类上添加@ImportResource注解,指定我们需要加载的xml配置文件
public class Springboot10Application {
public static void main(String[] args) {
SpringApplication.run(Springboot10Application.class, args);
}
}
测试:
@Autowired
private ApplicationContext applicationContext;
@Test
public void Test4(){
Cat cat = (Cat) applicationContext.getBean("cat");
System.out.println(cat);
}
成功打印出Cat类的toString: