Spring Boot推荐使用Java来完成相关的配置工作。
在项目中,不建议将所有的配置放在一个配置类中,可以根据不同的需求提供不同的配置类,例如专门处理Spring Security的配置类、提供Bean的配置类、Spring MVC相关的配置类。这些配置类上都需要添加@Configuration注解,@ComponentScan注解会扫描所有的Spring组件,也包括@Configuration。
@ComponentScan注解在项目入口类的@Spring BootApplication注解中已经提供,因此在实际项目中只需要按需提供相关配置类即可。
Spring Boot中并不推荐使用XML配置,建议尽量用Java配置代替XML配置。如果需要使用XML配置,只需在resources目录下提供配置文件,然后通过@ImportResource加载配置文件即可。例如,有一个Hello类如下:
Hello.java
package com.shrimpking.entity;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 22:38
*/
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 id="hello" class="com.shrimpking.entity.Hello"/>
</beans>
然后创建Beans配置类,导入XML配置:
package com.shrimpking.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 22:40
*/
@Configuration
@ImportResource("classpath:beans.xml")
public class Beans
{
}
最后在Controller中就可以直接导入Hello类使用了:
package com.shrimpking.controller;
import com.shrimpking.entity.Hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/4 22:41
*/
@RestController
public class HelloController
{
@Autowired
private Hello hello;
@GetMapping("/hello")
public String hello()
{
return hello.sayHello("XML配置方式");
}
}