Spring
1. Spring
1.1 简介
- Spring框架是由于软件开发的复杂性而创建的。
- 目的:解决企业应用开发的复杂性
- Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器框架。
maven依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
1.2 优点
- 开源的免费的框架(容器)
- 轻量级的,非入侵式的框架
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持
1.3 组成
1.4 拓展
-
Spring Boot
- 一个快速开发的脚手架
- 基于SpringBoot可以快速开发单个微服务
- 约定大于配置
-
Spring Cloud
- 基于SpringBoot实现
2. IOC理论推论
-
dao
- userDao ----->接口
- userDaoImp1 -----接口的一种实现
- userDaoImp2 -----接口的另一种实现
- userDaoImo3 -----接口的第三种实现
-
service
- userService
上为之前的架构,当userService需要选择不同的userDao实现是需要再dao层改变代码,但是添加set注入后,接口的选择就交给了service层。
private UserDao userDao;
public UserServiceImp(){
userDao=new UserDaoImp();
}
public userDao setUserDao(UserDao userDao){
this.userDao=userDao
}
- 之前,程序主动创建对象,控制权在程序员手中
- 使用set注入后,程序不再拥有主动性,而是被动的接收对象
这种思想,从本质上解决了问题,程序员不再管理用户的创建,系统的耦合性降低,更加专注于业务的实现。这就是IOC 思想的原型
3.IOC本质
控制反转,是一种设计思想,DI(依赖注入)是实现IOC的一种方法。也有人认为DI只是IOC的另一种说法,没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码再程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方。所谓的控制反转就是:获得依赖的对象方式反转了
4.IOC创建对象的方式
-
使用无参构造创建对象(默认!)
-
若使用有参构造创建对象
-
下标赋值
-
<bean id="hello" class="com.fish.pojo.Hello"> <constructor-arg index="0" value="hello"></constructor-arg> </bean>
-
使用类型匹配(不推荐使用,若是存在多个相同类型的参数,无法正常匹配)
-
<bean id="hello" class="com.fish.pojo.Hello"> <constructor-arg type="java.lang.String" value="hello"></constructor-arg> </bean>
-
直接通过参数名来设置
-
<bean id="hello" class="com.fish.pojo.Hello"> <constructor-arg name="str" value="hello"></constructor-arg> </bean>
-
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了
5 Spring配置
别名:
<alias name="hello" alias="hello2"></alias>
Bean的配置:
- id:相当于变量名
- class:实体的全限定名
- name:别名
<bean id="hello" class="com.fish.pojo.Hello" name="hello2">
<constructor-arg name="str" value="hello"></constructor-arg>
</bean>
import:
一般用户团队开发使用,可以将多个配置文件导入合并为一个
<import resource="beans.xml"></import>
6.依赖注入(DI)
- 构造器注入
- set方式注入【重点】
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中所有的属性,由容器注入
public class User {
private String name; //string
private Hello hello; //ref
private String[] books; //数组
private List<String> hobbys; //list集合
private Map<String,String> cards; //map集合
private Set<String> games; //set集合
private Properties info; //properties资源
private String wife; //空指针
}
<bean id="user" class="com.fish.pojo.User">
<!-- 普通值注入 -->
<property name="name" value="fish"></property>
<!-- bean注入 -->
<property name="hello" ref="hello"></property>
<!-- 数组注入 -->
<property name="books">
<array>
<value>book1</value>
<value>book2</value>
<value>book3</value>
</array>
</property>
<!-- list集合注入 -->
<property name="hobbys">
<list>
<value>hobby1</value>
<value>hobby2</value>
<value>hobby3</value>
</list>
</property>
<!-- map注入 -->
<property name="cards">
<map>
<entry key="k1" value="v1"></entry>
<entry key="k2" value="v2"></entry>
</map>
</property>
<!-- set注入 -->
<property name="games">
<set>
<value>g1</value>
<value>g2</value>
<value>g3</value>
</set>
</property>
<!-- null注入 -->
<property name="wife">
<null></null>
</property>
<!-- properties资源注入 -->
<property name="info">
<props>
<prop key="id">1</prop>
<prop key="sex">man</prop>
<prop key="gender">大二</prop>
</props>
</property>
</bean>
<bean id="hello" class="com.fish.pojo.Hello"></bean>
-
拓展方式注入
- p-namespace 需要添加xml约束:
xmlns:p="http://www.springframework.org/schema/p"
<bean id="helloBean" class="com.fish.pojo.Hello" p:str="hello"></bean>
- c-namespace xml约束
xmlns:c="http://www.springframework.org/schema/c"
<bean id="helloBean1" class="com.fish.pojo.Hello" c:str="hello-c-namespace"></bean>
7.bean作用域
-
singleton 单例模式(spring默认)
-
prototype 原型模式
- 每次从容器中get时都会产生一个新对象
-
其余的session,request,application,这些只能在web开发中使用
8.Bean的自动装配
- 自动装配:spring满足bean依赖的一种方式
- spring会在上下文自动寻找,并给bean装配属性
三种spring装配方式
- 在xml中显示的配置
- 在Java中显示配置
- 隐式的自动装配【掌握,重要】
<!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanID-->
<bean id="person" class="com.fish.pojo.Person" autowire="byName"></bean>
<bean id="cat" class="com.fish.pojo.Cat"></bean>
byType:弊端,必须保证类型全局唯一
<!--byType:会自动在容器上下文中查找,和自己对象set方法后面的值对应的类型属性-->
<bean id="person" class="com.fish.pojo.Person" autowire="byType"></bean>
<bean id="cat" class="com.fish.pojo.Cat"></bean>
小结:
- byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- byType的时候,需要保证所有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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
@Autowired
- 直接在属性上使用即可,也可以在set方法上使用
- 使用Autowired我们可以不用编写set方法,前提是自动装配的属性在IOC(spring)容器中存在且符合名字类型
- @Autowired(required = false):说明这个属性可以为空,否则不可,默认为true
@Nullable
- 字段标有该注解,说明这个字段可以为null
@Qualifier(value="")
-
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,可以使用@Qualifier(value=“xxxx”)来配合【@Autowired】使用,指定一个唯一的bean
-
@Autowired @Qualifier("cat1") private Cat cat;
@Resource
-
@Resource(name = "cat1") private Cat cat
@Resource和@Autowired的区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired是通过byType的方式实现的,而且必须要求对象存在【常用】
- @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到则报异常【常用】
9.使用注解开发
<!-- 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="com.fish.pojo"></context:component-scan>
@component :组件,放在类上,说明该类被spring管理了,就是bean
- 衍生的注解
- dao 【@Repository】
- service 【@Service】
- controller 【@Controller】
10.使用Java的方式配置spring
JavaConfig是spring的一个子项目
- @Import(“xxx.class”):导入配置类
- @ComponentScan(“com.fish.pojo”)
- @Configuration:代表一个配置类===xxx.xml
- @Bean:相当于bean标签
- 方法的名字相当于bean中id属性
- 返回值相当于bean中class属性
@Configuration
public class Config {
@Bean
public User getUser(){
return new User();
}
}
11.代理模式
springAOP的底层
代理模式的分类:
- 静态代理
- 动态代理
11.1静态代理
角色分析:
-
抽象角色:一般会使用接口或者抽象类来解决
-
public interface Rent { //抽象角色---干什么,租房 public void rent(); }
-
-
真实角色:被代理的角色
-
public class Host implements Rent{ //真实角色---房东 public void rent() { System.out.println("房东租房"); } }
-
-
代理角色:代理的真是角色,代理真实角色后,我们一般会做一些附属操作
-
//代理角色 public class Proxy implements Rent{ private Host host; public Proxy() { } public Proxy(Host host) { this.host = host; } public Host getHost() { return host; } public void setHost(Host host) { this.host = host; } public void rent() { host.rent(); } }
-
-
客户:访问代理对象的人
-
public class Client { public static void main(String[] args) { Host host = new Host();//选定房东 Proxy proxy = new Proxy(host);//中介 proxy.rent();//中介操作 } }
-
好处:
- 可以是真实角色的操作更加纯粹,不用去关注一些公共业务
- 公共业务就交给代理角色,实现业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色,代码量大
11.2动态代理
- 动态代理的代理类是动态的,不是直接写好的
- 动态代理分类
- 基于接口的动态代理:jdk动态代理
- 基于类的动态代理:cglib
- java字节码实现:javasist
两个类:
Proxy
提供了创建动态代理类和实例的静态方法,它也是由这些方法创建的所有动态代理类的超类。InvocationHandler
是由代理实例的调用处理程序实现的接口 。每个代理实例都有一个关联的调用处理程序。
动态代理类生成:
public class ProxyInvocationHandler implements InvocationHandler {
//需要代理的真实对象
private Object target;
//设置需要代理的真实对象
public void setTarget(Object target) {
this.target = target;
}
//获取代理对象
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}
客户操作:
public class Client {
public static void main(String[] args) {
//创建需要代理的对象
Host host = new Host();
//创建代理对象处理器
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//设置需要代理的真实对象
pih.setTarget(host);
//创建代理对象
Rent proxy = (Rent) pih.getProxy();
//代理对象执行
proxy.rent();
}
}
12 AOP
什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是spring框架中一个重要内容。是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率
在spring中的作用
声明式事务
spring中实现
依赖:
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<scope>runtime</scope>
</dependency>
使用springAPI接口实现
抽象角色:
public interface UserService {
void add();
void update();
void delete();
void search();
}
需要代理的真实角色:
public class UserServiceImp implements UserService {
public void add() {
System.out.println("add");
}
public void update() {
System.out.println("update");
}
public void delete() {
System.out.println("delete");
}
public void search() {
System.out.println("search");
}
}
代理角色:
public class ALog implements AfterReturningAdvice {
//o:返回值
//objects:args
//o1:target
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println(o1.getClass().getName() + "------" + method.getName() + "-----" + o);
}
}
public class BLog implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
// objects:参数
//o:target,目标对象
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName() + "-----" + method.getName());
}
}
将抽象对象,真实对象,代理对象添加至spring容器中,并在容器中配置aop
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="UserService" class="com.fish.service.UserServiceImp"/>
<bean id="BLog" class="com.fish.log.BLog"/>
<bean id="ALog" class="com.fish.log.ALog"/>
<!-- 配置aop 需要导入约束 -->
<aop:config>
<!-- 切入点 expression:表达式,execution(要执行的位置) -->
<aop:pointcut id="pointcut" expression="execution(* com.fish.service.UserServiceImp.*(..))"/>
<!-- 执行环绕添加 -->
<aop:advisor advice-ref="BLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="ALog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
execution表达式:
示例:execution(* com.sample.service.impl…*.*(…))
符号 | 含义 |
---|---|
**execution() ** | **表达式的主体; ** |
**第一个”*“符号 ** | **表示返回值的类型任意; ** |
com.sample.service.impl | AOP所切的服务的包名,即,我们的业务部分 |
包名后面的”…“ | 表示当前包及子包 |
第二个”*“ | 表示类名,*即所有类。此处可以自定义,下文有举例 |
.*(…) | 表示任何方法名,括号表示参数,两个点表示任何参数类型 |
自定义切面
<bean id="diy" class="com.fish.diy.DiyPointcut"/>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.fish.service.UserServiceImp.*(..))"/>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
切面:
public class DiyPointcut {
public void before(){
System.out.println("----before----");
}
public void after(){
System.out.println("----after----");
}
}
注解实现
@Aspect
public class AnoPointcut {
@Before("execution(* com.fish.service.UserServiceImp.*(..))")
public void before(){
System.out.println("----before----");
}
@After("execution(* com.fish.service.UserServiceImp.*(..))")
public void after(){
System.out.println("----after----");
}
@Around("execution(* com.fish.service.UserServiceImp.*(..))")
public void around(ProceedingJoinPoint point) throws Throwable {
System.out.println("----around-before----");
Object proceed = point.proceed();
System.out.println("----around-after----");
}
}
配置中开启自动代理
<bean id="anoPoint" class="com.fish.diy.AnoPointcut"/>
<aop:aspectj-autoproxy/>
13 MyBatis-Spring整合
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 一般写mybatis设置和别名设置-->
</configuration
整合spring和mybaits:applicationContext.xml
-
配置数据源
-
<bean id="dateResource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/smbms?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean>
-
-
创建sqlSessionFactory
-
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dateResource"/> <!-- 绑定mybatis配置文件--> <property name="configLocation" value="classpath:mybatis-Config.xml"/> <!-- mapper注册--> <property name="mapperLocations" value="classpath:com/fish/dao/*.xml"/> </bean>
-
-
创建sqlSession,使用sqlSessionTemplate和sqlSession无缝衔接
-
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </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">
<!-- 配置需要连接的数据库 使用spring提供的数据源来替代mybatis数据源 -->
<bean id="dateResource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/smbms?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 创建sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dateResource"/>
<!-- 绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-Config.xml"/>
<!-- mapper注册-->
<property name="mapperLocations" value="classpath*:com/fish/dao/*.xml"/>
</bean>
<!-- 创建sqlSessionTemplate:就是我们使用的sqlSession模板-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
注意:注册mapper时 如果要使用通配符,前置应为classpath*,而不是classpath
使用sqlSessionDaoSuppor,需要注入sqlSessionFactory
<!-- 使用sqlSessionDaoSupport-->
<bean id="userDao" class="com.fish.dao.UserMapperImp2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
继承SqlSessionDaoSupport,由SqlSessionDaoSupport代替我们创建sqlSession,我们只需注入sqlSessionFactory。
public class UserMapperImp2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUserList() {
return getSqlSession().getMapper(UserMapper.class).getUserList();
}
}
14 spring中的事务管理
- 声明式事务管理
- aop实现
- 编程式事务管理
- 在代码中手动添加事务,一般使用声明式事务
声明式事务:配置
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dateResource"/>
</bean>
<!-- 给哪些方法配置事务-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" />
</tx:attributes>
</tx:advice>
切面插入事务
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.fish.dao.*.*())"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
14 spring中的事务管理
- 声明式事务管理
- aop实现
- 编程式事务管理
- 在代码中手动添加事务,一般使用声明式事务
声明式事务:配置
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dateResource"/>
</bean>
<!-- 给哪些方法配置事务-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" />
</tx:attributes>
</tx:advice>
切面插入事务
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.fish.dao.*.*())"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>