Spring核心
- ioc (控制反转)
- aop(切面编程)
1、IOC
解决代码中耦合性偏高问题,比如我们在编程需要经常去实例化(new)一些重复性很高的对象,转换成我们从容器中去取已经实例化好的对象
一种解耦思想,将对象的实例化,初始化等教给ioc容器控制管理,容器中的对象叫做bean
1、xml方式
步骤:
第1步:导包 spring-context,可以传递spring-beans,spring-core,spring-expression依赖
第2步:创建xml配置文件,通过实例化UserServlet UserServiceImpl对象 通过注入UserServiceImpl对象
第3步:获取Spring IoC容器 ApplicationContext,加载xml配置文件
第4步:通过ApplicationContext getBean(“bean名称”,返回类型 )方法获取UserServiceImpl, UserServlet
搭建Spring开发环境 --> 从SpringIoc容器中获取bean —> 依赖注入指定bean
- 引入spring坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.17.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
- 定义Spring管理的类
public class UserServlet {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void save() {
userService.save();
}
}
public class UserServiceImplA implements UserService {
@Override
public void save() {
System.out.println("user service A save....");
}
}
public class UserServiceImplB implements UserService {
@Override
public void save() {
System.out.println("user service B save....");
}
}
- 创建Spring配置文件 , 配置对应类作为Spring管理的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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--定义UserServlet bean-->
<bean id="userServlet" class="com.itheima.web.UserServlet">
<property name="userService" ref="serviceImplB"/>
</bean>
<!--定义Service bean-->
<bean id="serviceImpl" class="com.itheima.service.impl.UserServiceImpl"></bean>
<bean id="serviceImplB" class="com.itheima.service.impl.UserServiceImplB"></bean>
</beans>
- 初始化IoC容器(Spring核心容器/Spring容器),通过容器获取bean
public class App {
@Test
public void testIOC() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserServlet userServlet = applicationContext.getBean("userServlet", UserServlet.class);
userServlet.save();
}
}
bean的实例化
- 普通bean实例化
- 工厂bean实例化
bean 的依赖注入
-
xml bean 的依赖注入2种方式
1、
2、 -
xml 的自动装配
2、注解
@component
@controller
@Service
@Repository
@configuration @bean
@propertySource @value