一篇文章带你搞定 SpringBoot 加载 XML配置

一、问题引入

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)结构图:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章