核心概念
IoC(Inversion of Control)——控制反转
使用对象时,由主动new产生对象转换为外部提供对象,此过程中对象创建控制权由程序转移到外部,此思想称为控制反转。
Spring技术实现了IoC思想。提供IoC容器,用来充当IoC思想中的“外部”。IoC容器负责对象的创建,初始化等一系列工作,被创建或管理的对象在IoC容器中统称为Bean。
DI(Dependency Injection)——依赖注入
在IoC容器中建立Bean与Bean之间依赖关系的整个过程,称之为依赖注入。
目标:充分解耦
- 使用IoC容器管理Bean
- 在IoC容器内将有依赖关系的Bean进行关系绑定
最终效果:使用对象时不仅可以直接从IoC容器中获取,并且获取到的Bean已经绑定了所有的依赖关系。
IoC实现思路
- 管理什么?——Bean(service、Dao等)
- 如何将被管理的对象告诉IoC容器?——配置文件
- 如何获取到IoC容器?——接口
- 拿到IoC容器后,如何获取到需要的Bean?——接口方法
- 使用Spring导入哪些坐标?——pom.xml
简单案例:
导入spring坐标spring-context(Maven工程)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
配置bean bean标签配置bean,id属性给bean起名字,class属性表示给bean定义类型
<?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">
<!-- 1.导入Spring坐标spring-context 对应版本5.2.10.RELEASE-->
<!-- 2.配置Bean-->
<bean id="testDao" class="tech.akboom.dao.impl.TestDaoImpl"/>
<bean id="testService" class="tech.akboom.service.impl.TestServiceImpl">
<!-- property标签表示配置当前bean的属性-->
<!-- name属性表示配置哪一个属性-->
<!-- ref属性表示参照哪一个bean-->
<property name="testDao" ref="testDao"/>
</bean>
</beans>
根据配置文件获取IOC容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
调用getBean方法获取bean
TestService testService=(TestServiceImpl)ctx.getBean("testService");
执行方法
testService.test();
DI的实现:
类中添加依赖和setter函数
private TestDao testDao;
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
再配置文件中配置属性
<bean id="testDao" name="Dao Dao1 Dao2" class="tech.akboom.dao.impl.TestDaoImpl"/>
<bean id="testService" class="tech.akboom.service.impl.TestServiceImpl" scope="prototype">
<!-- property标签表示配置当前bean的属性-->
<!-- name属性表示配置哪一个属性-->
<!-- ref属性表示参照哪一个bean-->
<property name="testDao" ref="Dao"/>
</bean>
Bean说明:
获取的bean默认为单例,便于容器管理。表现层对象,业务层对象,数据层对象,工具对象都适合交给容器管理,他们都只需要单例即可。封装实体的域对象不适合交给容器管理。