一、問題引入
SpringBoot 的主要思想是習慣大於配置
在實際應用開發過程中也會存在不得不添加配置文件的情況,例如集成其他框架或者需要配置一些中間件等,在這種情況下,就需要引入自定義的 xml 配置文件。
二、SpringBoot 加載 XML配置
(1)普通的 UserService:
public class UserService {
public String getUser(){
return "test xml";
}
}
(2)通過 applicationContext.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 class="com.example.favicon.UserService" id="userService"/>
</beans>
(3)建立配置類引入配置文件:WebMvcConfig
@Configuration
@ImportResource(locations = "classpath:applicationContext.xml")
public class WebMvcConfig {
}
其實也可以在啓動類上加註解:@ImportResource(locations = "classpath:applicationContext.xml")
引入配置文件,可以加多個配置文件
(4)控制器 UserController 訪問:
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/user")
public String getTest(){
return userService.getUser();
}
}
(5)結構圖: