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配置
