默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目中真的就无法导入 Spring 配置吗?答案是否定的。
Spring Boot 为了我们提供了以下 2 种方式来导入 Spring 配置:
使用 @ImportResource 注解加载 Spring 配置文件
使用全注解方式加载 Spring 配置
@ImportResource 导入 Spring 配置文件
在主启动类上使用 @ImportResource 注解可以导入一个或多个 Spring 配置文件,并使其中的内容生效。
- 主程序添加spring的配置文件路径
@ImportResource(locations={"classpath:beans.xml"})
- 编写beans.xml配置文件
<?xmlversion="1.0"encoding="UTF‐8"?>
<beansxmlns="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="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>
全注解方式加载 Spring 配置
Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:
/**
* @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
*/
@Configuration
publicclassMyAppConfig{
//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public HelloService helloService02(){
System.out.println("配置类@Bean给容器中添加组件了...");
return new HelloService();
}
使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。