Spring学习资料
Spring 简介
Spring是一个轻量级的控制反转和面向切面编程的框架。
-
2002年,首次推出了spring的雏形:interface21
-
2004年,正式发布了Spring 1.0版
-
理念:使现有技术更加容易使用
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>6.1.6</version> </dependency>
优点:
-
Spring 是一个轻量级、非入侵式的框架
-
控制反转(IOC)、面向切面(AOP)
-
支持事务的处理,对框架整合的支持
Spring组成
IOC
-
控制反转(IOC)是一种思想,依赖注入(DI)是实现控制反转的一种方式。控制反转即获得依赖对象的方式反转了,由程序转移到用户。
-
无IOC:我们使用面向对象编程,对象的创建与对象见的依赖关系完全硬编码在程序中,对象的创建由程序自己控制。
-
有IOC:我们使用面向对象编程,对象的创建转移给第三方。
-
IOC的注入方式(在配置文件加载时,容器中管理的对象就已经初始化了)
<?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"> <!--使用无参构造注入--> <bean id="user01" class="com.aug.bean.User"> <property name="name" value="帝尧"/> </bean> <!--使用有参构造注入:下标--> <bean id="user02_1" class="com.aug.bean.User"> <constructor-arg index="0" value="1"/> <constructor-arg index="1" value="帝舜"/> <constructor-arg index="2" value="19"/> </bean> <!--使用有参构造注入:类型--> <bean id="user02_2" class="com.aug.bean.User"> <constructor-arg type="java.lang.String" value="禹王"/> <constructor-arg type="int" value="2"/> <constructor-arg type="int" value="20"/> </bean> <!--使用有参构造注入:参数名--> <bean id="user02_3" class="com.aug.bean.User"> <constructor-arg name="id" value="3"/> <constructor-arg name="name" value="夏启"/> <constructor-arg name="age" value="21"/> </bean> </beans>
注入类型
<?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"> <bean id="user" class="com.aug.bean.User"> <!--第一种:普通值注入,value--> <property name="name" value="夏桀"/> <!--第二种:空值注入,value--> <property name="nullName"> <null/> </property> <!--第三种:bean注入,ref--> <property name="address" ref="address"/> <!--第四种:数组注入,array--> <property name="books"> <array> <value>甘誓</value> <value>汤誓</value> <value>汤诰</value> <value>康诰</value> </array> </property> <!--第五种:list注入,list--> <property name="hobbies"> <list> <value>弹琴</value> <value>下棋</value> <value>书法</value> <value>绘画</value> <value>吟诗</value> <value>喝酒</value> <value>赏花</value> </list> </property> <!--第六种:map注入,map--> <property name="card"> <map> <entry key="cardA" value="123456"/> <entry key="cardB" value="654321"/> </map> </property> <!--第七种:set注入,set--> <property name="games"> <set> <value>LOL</value> <value>BOB</value> </set> </property> <!--第八种:properties注入,set--> <property name="info"> <props> <prop key="driver">null</prop> <prop key="url">null</prop> <prop key="user">root</prop> <prop key="password">123456</prop> </props> </property> </bean> <bean id="address" class="com.aug.bean.Address"> <property name="address" value="洪荒"/> </bean> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--p标签注入--> <bean id="channel" class="com.aug.bean.Channel" p:channelNo="1" p:channelName="手太阴肺经" p:channelLyric="略"/> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--c标签注入--> <bean id="channel2" class="com.aug.bean.Channel" c:channelNo="2" c:channelName="手阳明大肠经" c:channelLyric="略"/> </beans>
bean的作用域
-
单例模式(spring 默认机制):每次从容器中get的时候,拿到的都是同一个对象
<bean id="accountService" class="com.something.DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default) --> <bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
-
原型模式:每次从容器种get的时候,都会产生一个新对象
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
-
其余模式:request、session、application只能在web开发中使用到
Bean的自动装配
-
自动装配式Spring满足bean依赖的一种方式
-
Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中的三种装配方式
-
在xml中显示配置
-
在java中显示配置
-
隐式地自动装配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"> <bean id="cat" class="com.aug.bean.Cat"/> <bean id="dog" class="com.aug.bean.Dog"/> <!--手动装配--> <bean id="people" class="com.aug.bean.People"> <property name="name" value="手动装配"/> <property name="cat" ref="cat"/> <property name="dog" ref="dog"/> </bean> </beans>
<?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"> <bean id="cat" class="com.aug.bean.Cat"/> <bean id="dog" class="com.aug.bean.Dog"/> <!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id--> <!--byName:需要保证bean的id唯一--> <bean id="people" class="com.aug.bean.People" autowire="byName"> <property name="name" value="自动装配"/> </bean> </beans>
<?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"> <bean class="com.aug.bean.Cat"/> <bean class="com.aug.bean.Dog"/> <!--byType:会自动在容器上下文中查找,和自己对象属性相同的bean--> <!--byType:需要保证bean的class唯一--> <bean id="people" class="com.aug.bean.People" autowire="byType"> <property name="name" value="自动装配"/> </bean> </beans>
注解实现自动装配
<?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/> <bean id="cat" class="com.aug.bean.Cat"/> <bean id="dog" class="com.aug.bean.Dog"/> <bean id="people" class="com.aug.bean.People"/> </beans>
package com.aug.bean; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; public class People { private String name; @Autowired private Cat cat; @Resource private Dog dog; public String getName() { return name; } public Cat getCat() { return cat; } public Dog getDog() { return dog; } }
小结:@Resource 和 @Autowired 的区别
-
但是用来自动装配的,都可以放在字段属性上
-
@Autowired 通过byType的方式实现
-
@Resource 默认通过byName的方式实现,如果找不到名字,则通过byType方式
使用注解开发
<?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/> <!--扫描包,使该包下的注解生效--> <context:component-scan base-package="com.aug.bean"/> </beans>
package com.aug.bean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component//等价于<bean id="user" class="com.aug.bean.User"/> public class User { @Value("注解开发") public String name; }
使用JavaConfig实现配置
package com.aug.config; import com.aug.bean.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; //@Configuration 代表这是一个配置类,等同于applicationContext.xml @Configuration public class UserConfig { //@Bean 等同于applicationContext.xml中的bean标签 //方法的名字等同于bean标签中的id属性 //方法的返回值等同于bean标签中的class属性 @Bean public User getUser(){ return new User();//注入到bean中的对象 } }
package com.aug.bean; import org.springframework.beans.factory.annotation.Value; public class User { private String name; public String getName() { return name; } @Value("JavaConfig实现配置") public void setName(String name) { this.name = name; } }
import com.aug.bean.User; import com.aug.config.UserConfig; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class); @Test public void test01(){ User user = (User) context.getBean("getUser"); System.out.println(user.getName()); } }
AOP
AOP是通过预编译方式和运行期动态代理实现程序功能的统一委会的一种技术。
AOP的作用
提供声明式事务,允许用户自定义切面。
-
横切关注点:跨越应用程序多个模块的方法或功能。与业务逻辑无关,但是我们需要注意的部分,就是横切关注点,如日志、安全、缓存、事务等。
-
切面(Aspect):横切关注点被模块化的特殊对象。它是一个类。
-
通知(Advice):切面必须要完成的工作。它是类中的一个方法。
-
目标(Target):被通知的对象。
-
代理(Proxy):向目标对象通知之后创建的对象。
-
切入点(PointCut):切面通知执行的“地点”的定义。
-
连接点(JoinPoint):与切入点匹配的执行点。
spring AOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice
AOP的实现方式
方式一:使用Spring的API接口
<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.aug.service.UserServiceImpl"/> <bean id="log" class="com.aug.log.Log"/> <!--配置aop:需要导入aop的约束--> <aop:config> <!--切入点:expression="excution(要执行的位置 修饰词 返回值 类名 方法名 参数)"--> <aop:pointcut id="pointcut" expression="execution(* com.aug.service.UserServiceImpl.*(..))"/> <!--执行环绕增加--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> </aop:config> </beans>
package com.aug.log; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class Log implements MethodBeforeAdvice, AfterReturningAdvice { /** * * @param method 要执行的目标对象的方法 * @param objects 参数 * @param o 目标对象 * @throws Throwable */ public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println("前置通知:"+o.getClass().getName()+"的"+method.getName()+"被执行了"); } /** * * @param o 返回值 * @param method 要执行的目标对象的方法 * @param objects 参数 * @param o1 目标对象 * @throws Throwable */ public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable { System.out.println("后置通知:执行了"+method.getName()+"返回结果为:"+o); } } =============================================================================== package com.aug.service; public interface UserService { public void select(); public void insert(); public void update(); public void delete(); } =============================================================================== package com.aug.service; public class UserServiceImpl implements UserService{ public void select() { System.out.println("查询"); } public void insert() { System.out.println("新增"); } public void update() { System.out.println("修改"); } public void delete() { System.out.println("删除"); } } =============================================================================== import com.aug.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test01(){ //动态代理,代理的是接口 UserService userService = (UserService) context.getBean("userService"); userService.select(); } } ==========================执行输出============================================= 前置通知:com.aug.service.UserServiceImpl的select被执行了 查询 后置通知:执行了select返回结果为:null
方式二:使用自定义类实现AOP
<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.aug.service.UserServiceImpl"/> <!--方式二:自定义类--> <bean id="diy" class="com.aug.log.DiyLog"/> <aop:config> <!--自定义切面,ref为要引用的类--> <aop:aspect ref="diy"> <!--切入点--> <aop:pointcut id="point" expression="execution(* com.aug.service.UserServiceImpl.*(..))"/> <!--通知--> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config> </beans>
package com.aug.log; public class DiyLog { public void before(){ System.out.println("==========前置通知=========="); } public void after(){ System.out.println("==========后置通知=========="); } } =============================================================================== package com.aug.service; public interface UserService { public void select(); public void insert(); public void update(); public void delete(); } =============================================================================== package com.aug.service; public class UserServiceImpl implements UserService{ public void select() { System.out.println("查询"); } public void insert() { System.out.println("新增"); } public void update() { System.out.println("修改"); } public void delete() { System.out.println("删除"); } } =============================================================================== import com.aug.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test01(){ //动态代理,代理的是接口 UserService userService = (UserService) context.getBean("userService"); userService.select(); } } ==========================执行输出============================================= ==========前置通知========== 查询 ==========后置通知==========
方式三:使用注解方式实现AOP
<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.aug.service.UserServiceImpl"/> <!--方式三:使用注解实现AOP--> <bean id="annotationLog" class="com.aug.log.AnnotationLog"/> <!--开启注解支持--> <aop:aspectj-autoproxy/> </beans>
package com.aug.log; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect//标注这个类是一个切面 public class AnnotationLog { @Before("execution(* com.aug.service.UserServiceImpl.*(..))") public void before(){ System.out.println("======注解实现AOP:前置通知====="); } @After("execution(* com.aug.service.UserServiceImpl.*(..))") public void after(){ System.out.println("======注解实现AOP:后置通知====="); } @Around("execution(* com.aug.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint joinPoint){ System.out.println("======环绕前======"); try { joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } System.out.println("======环绕后======"); } } =============================================================================== package com.aug.service; public interface UserService { public void select(); public void insert(); public void update(); public void delete(); } =============================================================================== package com.aug.service; public class UserServiceImpl implements UserService{ public void select() { System.out.println("查询"); } public void insert() { System.out.println("新增"); } public void update() { System.out.println("修改"); } public void delete() { System.out.println("删除"); } } =============================================================================== import com.aug.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test01(){ //动态代理,代理的是接口 UserService userService = (UserService) context.getBean("userService"); userService.select(); } } ==========================执行输出============================================= ======环绕前====== ======注解实现AOP:前置通知===== 查询 ======环绕后====== ======注解实现AOP:后置通知=====