springboot XML配置

Spring Boot推荐使用Java来完成相关的配置工作。在项目中,不建议将所有的配置放在一个配置类中,可以根据不同的需求提供不同的配置类,例如专门处理Spring Security的配置类、提供Bean的配置类、Spring MVC相关的配置类。这些配置类上都需要添加@Configuration注解,@ComponentScan注解会扫描所有的Spring组件,也包括@Configuration。@ComponentScan注解在项目入口类的@Spring BootApplication注解中已经提供,因此在实际项目中只需要按需提供相关配置类即可。

Spring Boot中并不推荐使用XML配置,建议尽量用Java配置代替XML配置

如果开发者需要使用XML配置,只需在resources目录下提供配置文件,然后通过@ImportResource加载配置文件即可。

 

例如,有一个Hello类如下:

1
2
3
4
5
6
7
public class Hello {
 
    public String sayHello(String name) {
        return "hello " + name;
    }
 
}

在resources目录下新建beans.xml文件配置该类:

1
2
3
4
5
6
7
<?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.xc.xcspringboot.model.Hello" id="hello"/>
</beans>

然后创建Beans配置类,导入XML配置:

1
2
3
4
@Configuration
@ImportResource("classpath:beans.xml")
public class BeansConfiguration {
}

最后在Controller中就可以直接导入Hello类使用了:

1
2
3
4
5
6
7
8
9
@RestController
public class HelloController {
    @Autowired
    Hello hello;
    @GetMapping("/hello")
    public String hello() {
        return hello.sayHello("罗贯中");
    }
}

  

文章来源:Spring Boot+Vue全栈开发实战 - 4.7 配置类与XML配置  

posted @   草木物语  阅读(1564)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示