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类如下:
public class Hello { public String sayHello(String name) { return "hello " + name; } }
在resources目录下新建beans.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.xc.xcspringboot.model.Hello" id="hello"/> </beans>
然后创建Beans配置类,导入XML配置:
@Configuration @ImportResource("classpath:beans.xml") public class BeansConfiguration { }
最后在Controller中就可以直接导入Hello类使用了:
@RestController public class HelloController { @Autowired Hello hello; @GetMapping("/hello") public String hello() { return hello.sayHello("罗贯中"); } }
文章来源:Spring Boot+Vue全栈开发实战 - 4.7 配置类与XML配置