默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目如何导入 Spring 配置?
Spring Boot 为了我们提供了以下 2 种方式来导入 Spring 配置:
使用 @ImportResource 注解加载 Spring 配置文件
使用全注解方式加载 Spring 配置
1) @ImportResource 导入 Spring 配置文件
在主启动类上使用 @ImportResource 注解可以导入一个或多个 Spring 配置文件,并使其中的内容生效。
package com.example.springdemo.service;
public interface PersonService {
}
package com.example.springdemo.service;
public class PersonServiceImpl implements PersonService{
public String getMsg() {
return "person";
}
}
package com.example.springdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = {"classpath:/bean.xml"})
@SpringBootApplication
public class SpringdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringdemoApplication.class, args);
}
}
测试案例
package com.example.springdemo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class HelloworldApplicationTests {
//IOC 容器
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService() {
//校验 IOC 容器中是否包含组件 personService
boolean b = ioc.containsBean("personService");
if (b) {
System.out.println("personService 已经添加到 IOC 容器中");
} else {
System.out.println("personService 没添加到 IOC 容器中");
}
}
}
测试结果
2) 全注解方式加载 Spring 配置
Spring Boot 推荐使用全注解的方式加载 Spring 配置,其实现方式如下:
(1) 使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
(2) 配置类内部定义一个或多个被 @Bean 注解的方法;
(3) AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描和构建 bean 定义(相当于 Spring 配置文件中的<bean></bean>标签);
(4) @Bean 注解方法的返回值以组件的形式添加到容器中,组件的 id 就是方法名。
示例,删除@ImportResource ,新增AppConfig位置文件,内容如下。
package com.example.springdemo.conf;
import com.example.springdemo.service.PersonService;
import com.example.springdemo.service.PersonServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public PersonService personService() {
return new PersonServiceImpl();
}
}