SpringBoot 官方提倡零配置,不推荐使用 xml 配置,但是有的时候可能必须要使用 xml 配置,所以可以使用 @ImportResource 导入 xml 配置。
一、定义一个类
DemoService.java
package com.example.springbootboot02config.service;
/**
* @author liyanan
* @date 2019/12/22 20:03
*/
public class DemoService {
public void add() {
System.out.println("add() ...");
}
}
二、在 xml 文件声明对象
demo.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="demoService" class="com.example.springbootboot02config.service.DemoService">
</bean>
</beans>
在 xml 声明 demoService 对象。
三、加载 xml 配置
在 SpringBoot 启动类上使用 @ImportResource 注解的 locations 属性加载 xml 配置,将 demoService 加载入 Spring 容器。
package com.example.springbootboot02config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = {"classpath:demo.xml"})
@SpringBootApplication
public class SpringbootBoot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootBoot02ConfigApplication.class, args);
}
}
四、测试是否已将 xml 的配置加载入 Spring 容器中
package com.example.springbootboot02config;
import com.example.springbootboot02config.bean.Demo;
import com.example.springbootboot02config.bean.Emp;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class SpringbootBoot02ConfigApplicationTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void testDemoService() {
Object demoService = applicationContext.getBean("demoService");
assertNotNull(demoService);
}
}
测试通过,证明此事 Spring 容器中已经成功注入 demoService 对象。