导入Spring配置
默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目中真的就无法导入 Spring 配置吗?答案是否定的。
SpringBoot给我们提供了两种导入Spring配置的方式:
-
使用@ImportResource注解加载Spring配置
-
使用全注解的方式加载Spring配置
@ImportResource
在主启动类使用@ImportResource注解可以导入一个或多个Spring配置文件,并将其中的内容生效
实现
- 在项目中com.liang.service创建personService的接口,代码如下:
public interface PersonService {
public Person getPerson();
}
- 在项目中com.liang.service创建personService的实现类personServiceImpl,代码如下:
public class PersonServiceImpl implements PersonService{
@Autowired
private Person person;
@Override
public Person getPerson() {
return person;
}
}
3.在项目中resources下创建application.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="personService" class="com.liang.service.PersonServiceImpl"></bean>
</beans>
- 测试单元代码
//自动装配
@Autowired
private Person person;
//IOC容器
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(){
//校验IOC容器中是否包含组件personService
boolean flag= ioc.containsBean("personService");
if(flag){
System.out.println("personService已经在容器中");
}else{
System.out.println("personService不在容器中");
}
}
@Test
void contextLoads() {
System.out.println(person);;
}
-
运行
发现没有达到预想要求,而且实现类识别不了person -
主启动程序类
添加以下注解:
@ImportResource(locations = {"classpath:/beans.xml"})
- 再次执行代码
全注解方式
Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:
- 使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
- 配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。
代码部分
import com.liang.service.PersonService;
import com.liang.service.PersonServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration 注解用于定义一个配置类,相当于 Spring 的配置文件
* 配置类中包含一个或多个被 @Bean 注解的方法,该方法相当于 Spring 配置文件中的 <bean> 标签定义的组件。
*/
@Configuration
public class MyAppConfig {
/**
* 与 <bean id="personService" class="PersonServiceImpl"></bean> 等价
* 该方法返回值以组件的形式添加到容器中
* 方法名是组件 id(相当于 <bean> 标签的属性 id)
*/
@Bean
public PersonService personService() {
System.out.println("在容器中添加了一个组件:peronService");
return new PersonServiceImpl();
}
}