文章目录
一、简介
1.1什么是Spring?
- Spring-春天
- 是2002年首次推出的Spring框架,初代只是一个雏形:intuerface框架
- Spring是以interface框架为基础,经过重新设计,于2004年3月份发布的正式版
- Spring 理念:使现有的技术更加容易使用。Spring本身就是一个大杂烩,融合了现有的技术框架
- SSH是什么?-Struct2 + Spring + Hibernate
- SSM是什么?-SpringMVC + Spring + Mybatis
官方相关依赖:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
1.2 优点
- Spring 是一个开源的框架(免费)
- Spring 是一个轻量级的、非侵入式的框架
- 控制反转(IOC)、面向切面编程(AOP)
- 支持对事物的处理,对框架整合支持
总结:Spring 是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!
1.3 Spring 组成
1.4 拓展
现代化的Java开发,基本上就是基于 Spring 的开发!
- Spring Boot
- 一个快速开发的脚手架。
- 基于Spring Boot可以快速开发单个微服务
- 预定大于配置
- Spring Cloud
- Spring Cloud是基于Spring Boot实现的
现在大多数的公司都是基于Spring Boot开发的,学习Spring Boot之前。需要掌握对 Spring 和 Spring MVC。
缺点:发展的时间久了,配置起来很是繁琐。
二、IOC 的推导理论
2.1 创建 UserDao 接口
public interface UserDao {
void getUser();
}
2.2 创建UserDaoImpl 实现类
public class UserDaoImpl implements UserDao{
public void getUser(){
System.out.println("获取用户默认数据");
}
}
2.3 创建 UserService 接口
public interface UserService {
public void getUser();
}
2.4 创建 UserService 实现类
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImpl();
public void getUser(){
userDao.getUser();
}
}
2.5 测试
public class MyTest {
public static void main(String[] args) {
//用户实际调用的业务层,dao层不需要实际接触
UserServiceImpl userService = new UserServiceImpl();
userService.getUser();
}
}
- 结果:
2.6 项目结构
2.7 总结
在之前的代码中,用户的需求有可能会影响到源代码,需要根据用户的需求去修改源代码,修改代码的成本很大
利用 Set 动态实现,发生了革命性的变化
private UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public class MyTest {
public static void main(String[] args) {
//用户实际调用的业务层,dao层不需要实际接触
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoImpl());
userService.getUser();
}
}
这种思想,不用程序员再去管理对象的创建。大大降低了系统耦合性,可以更加关注业务上的实现。
三、Hello Spring
3.1 新建maven项目,实体类编写
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"string='" + str + '\'' +
'}';
}
}
3.2 配置 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">
<!--使用spring来创建对象,在spring中这些都成为Bean
类型类型 变量名 = new 类型
id = 变量名
class = new的对象
property 相当于给对象中的属性设置一个值!
-->
<bean id="hello" class="com.sisongpo.pojo.Hello">
<property name="str" value="Spring">
</property>
</bean>
</beans>
3.3 测试
public class Mytest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在Spring中管理了,直接去里面取出来就可以
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
}
3.4 结果
思考问题:
- Hello对象是谁创建的? 是由Spring创建的
- Hello对象的属性是怎么设置的?
是由 Spring 容器设置的
这个过程就是控制反转。
依赖注入: 利用set方法进行注入
四、IOC创建对象的方式
4.1 使用无参方式创建对象,默认!
public class User {
private String name;
private int age;
private int sex;
public User() {
System.out.println("无参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public void show(){
System.out.println("name='" + name + '\'' +
", age=" + age +
", sex=" + sex );
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
'}';
}
}
测试:
public class Mytest {
public static void main(String[] args) {
User user = new User();
System.out.println(user);
}
}
结果:
只要 new 对象,就是无参构造方法
4.2 有参构造
1、下标赋值
</bean>
<!-- 第一种方式:下标赋值-->
<bean id="user" class="com.sisongpo.pojo.User">
<!-- <property name="name" value="司松坡"/>-->
<constructor-arg index="0" value="司松坡"/>
</bean>
结果:
2、类型
<bean id="user" class="com.sisongpo.pojo.User">
<constructor-arg type="java.lang.String" value="司松坡"/>
</bean>
3、参数名
<bean id="user" class="com.sisongpo.pojo.User">
<constructor-arg name="name" value="司松坡"/>
</bean>
五、Spring配置
5.1 别名
<!-- 用了别用,可以通过别名调取-->
<alias name="user" alias="aaaaaa"/>
User user111 = (User) classPathXmlApplicationContext.getBean("aaaaaa");
System.out.println(user111.toString());
5.2 Bean 配置
<!--
id:bean的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的全限定名:包名+类名
name:也是别名,而且name可以同时取多个别名
-->
<bean id="user" class="com.sisongpo.pojo.User">
<constructor-arg name="name" value="司松坡"/>
</bean>
5.3 import
这个import。一般用于团队开发使用,它可以将多个配置文件,导入合并为一个。
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!
<import resource="bean.xml"/>
<import resource="bean2.xml"/>
<import resource="bean3.xml"/>
六、依赖注入
6.1 构造器注入
参考 四、IOC创建对象的方式
6.2 Set 方法注入
- 依赖注入:set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
1.复杂类型(新建类)
普通
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
复杂
package com.kuang.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbies=" + hobbies +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
2、编写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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring这些都称为Bean
类型 变量名 = new 类型();
Hello hello = new Hello();
id = 变量名
class = new的对象
property 相当于给对象中的属性设置一个值!
-->
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="青岛"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!-- 第一种:普通值注入-->
<property name="name" value="你是我的眼"/>
<property name="address" ref="address"/>
<!-- 数组-->
<property name="books">
<array>
<value>红楼梦</value>
<value>三国演义</value>
<value>水浒传</value>
<value>西游记</value>
</array>
</property>
<!-- map-->
<property name="card">
<map>
<entry key="身份证" value="412716418276481"/>
<entry key="银行卡" value="3254837562876581"/>
</map>
</property>
<!-- set-->
<property name="games">
<set>
<value>LoL</value>
<value>王者荣耀</value>
<value>CSGO</value>
</set>
</property>
<!-- list-->
<property name="hobbies">
<list>
<value>打游戏</value>
<value>打乒乓球</value>
</list>
</property>
<!-- Properties-->
<property name="info">
<props>
<prop key="derver">20220516</prop>
<prop key="url">202.196.64.1</prop>
<prop key="user">你是我的唯一</prop>
<prop key="password">123456</prop>
</props>
</property>
<property name="wife">
<null/>
</property>
</bean>
</beans>
3、测试
import com.kuang.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("bean1.xml");
Student student = (Student) classPathXmlApplicationContext.getBean("student");
System.out.println(student.toString());
}
}
4、结果
6.3 其他方式注入
可以使用 p 命名空间和 c 命名空间进行注入。
空间约束。
1、新建类
package com.kuang.pojo;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2、p 命名空间
首先导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
使用
3、c 命名空间
引入xml约束
xmlns:c="http://www.springframework.org/schema/c"
使用(需要构造器)
package com.kuang.pojo;
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
编写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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.kuang.pojo.User" p:name="我爱你" p:age="18" />
<!--c命名空间注入,通过构造器注入:constructor-args-->
<bean id="user2" class="com.kuang.pojo.User" c:name="我爱他" c:age="17"/>
</beans>
测试
import com.kuang.pojo.Student;
import com.kuang.pojo.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("UserBean.xml");
User user1 = (User) classPathXmlApplicationContext.getBean("user");
System.out.println(user1.toString());
User user2 = (User) classPathXmlApplicationContext.getBean("user2");
System.out.println(user2.toString());
}
}
结果
6.4 bean 的作用域
中文
- 单例模式(spring默认机制)
<bean id="user" class="com.kuang.pojo.User" p:name="我爱你" p:age="18" scope="singleton"/>
- 原型模式:每次从容器中get的时候,都会产生一个新的对象
<bean id="user2" class="com.kuang.pojo.User" c:name="我爱他" c:age="17" scope="prototype"/>
测试:
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("UserBean.xml");
User user1 = classPathXmlApplicationContext.getBean("user",User.class);
System.out.println(user1.toString());
User user2 = classPathXmlApplicationContext.getBean("user",User.class);
System.out.println(user2.toString());
System.out.println(user1==user2);
User user3 = classPathXmlApplicationContext.getBean("user2",User.class);
System.out.println(user3.toString());
User user4 = classPathXmlApplicationContext.getBean("user2",User.class);
System.out.println(user4.toString());
System.out.println(user3==user4);
}
}
结果
- 其余的request、session、application,这些在Web开发中使用到。
七、Bean 自动装配
- 自动装配是 Spring 满足 bean 依赖的一种方式
- Spring 会在上下文自动寻找,并自动给bean装配属性
在 Spring 中有三种装配的方式:
1、在 xml 中显式配置
2、在 Java 中显式配置
3、隐式的自动装配配置(重要)
7.1 测试
环境搭建:创建项目,一个人有两个宠物
Dog
public class Dog {
public void show(){
System.out.println("汪汪汪。。。。。");
}
}
Cat
public class Cat {
public void show(){
System.out.println("喵喵喵。。。。。");
}
}
People
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
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="cat" class="com.si.pojo.Cat"/>
<bean id="dog" class="com.si.pojo.Dog"/>
<bean id="people" class="com.si.pojo.People">
<property name="name" value="唯一"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
</beans>
测试
public class MyTest {
@Test
public void test1(){
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("People.xml");
People people = classPathXmlApplicationContext.getBean("people", People.class);
people.getDog().show();
people.getCat().show();
}
}
结果
7.2 ByName 自动装配
<bean id="cat" class="com.si.pojo.Cat"/>
<bean id="dog" class="com.si.pojo.Dog"/>
<!-- ByName 会自动查找在容器中上下文查找,和自己对象set方法后面的值对应的 beanId-->
<bean id="people" class="com.si.pojo.People" autowire="byName">
<property name="name" value="唯一"/>
<!-- <property name="cat" ref="cat"/>-->
<!-- <property name="dog" ref="dog"/>-->
</bean>
7.3 ByType 自动装配
<!-- byType 会自动在容器上下文寻找,和自己对象属性类型相同的bean-->
<bean id="people" class="com.si.pojo.People" autowire="byType">
<property name="name" value="唯一"/>
</bean>
总结:
- ByName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- ByType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
7.4 使用注解实现自动装配
前言: JDK 1.5 支持注解,Spring 2.5 后支持注解
须知:
1、导入约束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:contest="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
2、配置注解支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:contest="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<contest:annotation-config></contest:annotation-config>
</beans>
@Autowired
直接在属性上进行使用,也可以在 set 方法上进行使用
使用 Autowired 可以不用编写 set 方法,前提是这个自动配置的属性在IOC(Spring)容器中存在,且符合名字ByName
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
注意: 使用 @Nullable 字段标记了这个注解,说明这个字段可以为 null
可以后跟属性,required
//如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Resource
@Resource
private Cat cat;
@Resource
private Dog dog;
private String name;
@Autowired 和 @Resource 区别
- 都是用来自动装配的,都可以放在字段上
- @Autowired 通过 byType 的方式进行实现的,而且必须要求这个对象存在!
- @Resource默认通过 byName 的方式实现,如果找不到名字,则通过 byType 的方式实现!如果两个都找不到的情况下,报错!
- 执行顺序不同,@Autowired 通过 byType 的方式进行实现
八、使用注解开发
在spring 4 之后,要使用注解开发,必须要保证 aop 的包导入
需要在Xml中导入约束配置,和使用注解自动装配的约束配置一样
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:contest="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解支持-->
<contest:annotation-config></contest:annotation-config>
</beans>
8.1 bean
8.2 属性如何注入
// 等价于<bean id="auto" class="com.si.pojo.Auto"/>
// @Component组件
@Component
public class Auto {
//等价于 <property name="name" value="唯一"/>
@Value("唯一")
public String name;
}
8.3衍生的注解
@Component 有几个衍生注解,我们在 Web 开发中,会按照 MVC 三层架构分层。
//dao [@Repository]
//service [@Service]
//controller [@Controller]
这四个注解功能都是一样的,都是代表把某个类注册到 Spring 中,用来装配 Bean。
8.4自动装配
@Autowired:自动装配通过类型,名字。如果Autowired不能唯一自动装配上属性,则需要通过 @Qualifier(value = "xxx") 去配置。
@Nullable:字段标记了了这个注解,说明这个字段可以为null;
@Resource:自动装配通过名字,类型。
8.5作用域
// 等价于<bean id="auto" class="com.si.pojo.Auto"/>
// @Component组件
@Component
@Scope("singleton")
public class Auto {
//等价于 <property name="name" value="唯一"/>
@Value("唯一")
public String name;
}
测试:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = (ApplicationContext) new ClassPathXmlApplicationContext("Auto.xml");
Auto name = (Auto) context.getBean("auto");
System.out.println(name.toString());
}
}
结果:
8.6 总结
xml 与注解:
xml 更加万能,适用于任何场景,维护简单方便
注解不是自己类使用不了
xml 与注解最佳实践:
xml 用来管理 bean;
注解只负责属性注入
使用前提:开启注解生效
九、使用 Java 的方式配置 Spring
现在完全不使用 Spring 的 xml 配置,全权交给 Java 来做
JavaConfig 是 Spring 下面的一个子项目,在 Spring 4 之后,成为了一个核心功能
9.1 配置文件
package com.si.config;
import com.si.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public User getUser(){
return new User();
}
}
9.2 实体类
package com.si.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
@Controller
public class User {
private String name;
public String getName() {
return name;
}
@Value("唯一")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
9.3 测试
import com.si.config.MyConfig;
import com.si.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.toString());
}
}
9.4 结果
小结:这种配置在 springboot 中随处可见
十、代理模式
SpringAOP 的底层就是代理模式(SpringAOP 和 SpringMVC)
10.1 代理模式的分类
- 静态代理
- 动态代理
10.2 静态代理
角色分析:
3. 抽象角色:一般使用接口或者抽象类来解决
4. 真实角色:被代理的对象
5. 代理角色:代理真实角色,代理真实角色后,我们一般会有一些负数操作
6. 客户:访问代理对象的人
代码步骤:
- 设置接口
//编写接口
public interface Rent {
public void tent();
}
- 实例
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东出租房子~~~~");
}
}
- 代理角色
package com.si.pojo;
//代理角色
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
host.rent();
seHouse();
fee();
sign();
}
//看房
public void seHouse(){
System.out.println("中介带你看房~~~");
}
//签合同
public void sign(){
System.out.println("签合同~~~");
}
//收费用
public void fee(){
System.out.println("中介收取费用~~~");
}
}
- 客户端访问代理对象
public class Client {
public static void main(String[] args) {
//房东要出租房子
Host host = new Host();
host.rent();
//代理
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
- 结果
总结:
代理的好处: - 可以使真是角色操作更加纯粹,不用关注其他的业务
- 公共角色就交给代理角色,实现了业务的分离
- 公共业务发生扩展的时候,方便集中管理
缺点:
一个角色就会产生一个代理类,代码量会增大
10.3 动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口:JDK动态代理 【在这里使用】
- 基 于 类 :cglib(CGLIB(Code Generation Library)是一个开源项目。
是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口。Hibernate支持它来实现PO(Persistent Object 持久化对象)字节码的动态生成。)待学习
- java 字节码实现:javassist(Javassist是一个开源的分析、编辑和创建Java字节码的类库。)待学习
需要了解两个类:
- Proxy:代理;
- InvocationHandler:调用处理程序。
代码步骤:
- 接口(和静态代理一样)
public interface Rent {
public void rent();
}
- 真实角色(和静态代理一样)
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东出租房子~~~~");
}
}
- ProxyInvocationHandler类
package com.si.pojo;
import org.springframework.cglib.proxy.Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyInvocationHandler implements InvocationHandler{
//被代理接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this::invoke);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理本质,使用反射机制实现
Object result = method.invoke(rent,args);
seHouse();
sign();
fee();
return result;
}
//看房
public void seHouse(){
System.out.println("中介带你看房~~~");
}
//签合同
public void sign(){
System.out.println("签合同~~~");
}
//收费用
public void fee(){
System.out.println("中介收取费用~~~");
}
}
- 测试
import com.si.pojo.Host;
import com.si.pojo.ProxyInvocationHandler;
import com.si.pojo.Rent;
public class MyTest1 {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色,现在没有
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
//通过调研用程序处理角色来处理我们要调用的接口对象
proxyInvocationHandler.setRent(host);
Rent proxy = (Rent) proxyInvocationHandler.getProxy();//这里的proxy 是动态生成的,并没有写
proxy.rent();
}
}
- 结果
动态代理的好处: - 可以使真实的角色操作更加纯粹,不用关注一些公众的业务
- 公众角色皆可以交给代理角色,实现业务的分工
- 业务发生扩展的时候,方便集中管理
- 一个动态代理指一个窗口,一般对应的是一个业务
- 一个动态代理类可以代理多个类,只要实现一个借口即可
十一、AOP
11.1 什么是 AOP ?
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2 AOP 在 Spring 中的使用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
- 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知执行的“地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
Spring AOP 提供了五种类型的 Advice:
- 环绕通知:方法前后
- 前置通知:方法前
- 后置通知:方法后
- 异常抛出通知:方法抛出异常
- 最终通知:方法执行后
11.3 使用 Spring 实现AOP
【重点】使用 AOP 织入,需要导入依赖包
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
方式一: 使用 Spring 的 API 接口
- 在 service 包下,定义 UserService 业务接口和 UserServiceImpl 实现类
package com.si.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
package com.si.service;
public class UserServiceImpl implements UserService{
//增加一个用户
@Override
public void add() {
System.out.println("增加一个用户");
}
//删除一个用户
@Override
public void delete() {
System.out.println("删除一个用户");
}
//修改一个用户
@Override
public void update() {
System.out.println("修改一个用户");
}
//查询一个用户
@Override
public void select() {
System.out.println("查询一个用户");
}
}
- 在 log 包下,定义增强类,一个 Log 前置增强和一个 AfterLog后置增强类
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//args:参数
//target:目标对象
@Override
public void before(Method method, Object[] agrs, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] agrs, Object target) throws Throwable {
System.out.println("执行了" + method.getName() + "方法,"+"返回的结果为"+returnValue);
}
}
- 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"
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.si.service.UserServiceImpl"/>
<bean id="log" class="com.si.log.Log"/>
<bean id="afterLog" class="com.si.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式,execution(要执行的位置!* * * * *)-->
<aop:pointcut id="pointcut" expression="execution(* com.si.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加!-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
- 测试
public class MyTest1 {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色,现在没有
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
//通过调研用程序处理角色来处理我们要调用的接口对象
proxyInvocationHandler.setRent(host);
Rent proxy = (Rent) proxyInvocationHandler.getProxy();//这里的proxy 是动态生成的,并没有写
proxy.rent();
}
}
**方式二:**自定义类实现AOP
- 在包下定义自己的切入类
增强方法:
public class Ssp {
public void before(){
System.out.println("方法执行前:+" + new Date());
}
public void after(){
System.out.println("方法执行后:+" + new Date());
}
}
实体类:
public class SspMain {
public void printSsp(){
System.out.println("正在打印唯一");
}
}
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"
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">
<!-- 方式二:自定义类-->
<?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 id="sspMain" class="com.si.ssp.SspMain"/>
<bean id="ssp" class="com.si.ssp.Ssp"/>
<aop:config>
<!-- 自定义切面 ref需要引入的类-->
<aop:aspect ref="ssp">
<!-- 切入点-->
<aop:pointcut id="pointSsp" expression="execution(* com.si.ssp.*.*(..))"/>
<!-- 通知-->
<aop:before method="before" pointcut-ref="pointSsp"/>
<aop:after method="after" pointcut-ref="pointSsp"/>
</aop:aspect>
</aop:config>
</beans>
测试:
public class SspTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SspMain.xml");
SspMain sspMain = (SspMain) context.getBean("sspMain");
sspMain.printSsp();
}
}
结果:
**方式三:**使用注解实现
- 在包下定义注解实现的增强类
//声明式事务
@Aspect //标注这个类是一个切面
public class Test1Impl{
@Before("execution(* com.si.test1.Test1.*(..))")
public void befor(){
System.out.println("方法执行前~~~");
}
@After("execution(* com.si.test1.Test1.*(..))")
public void after(){
System.out.println("方法执行后~~~");
}
@Around("execution(* com.si.test1.Test1.*(..))")
//环绕通知=前置+目标方法执行+后置通知,proceed方法就是用于启动目标方法执行的
public void around(ProceedingJoinPoint jp) throws Throwable{
System.out.println("环绕前~~~");
Signature signature = jp.getSignature();//获得签名
System.out.println("signature:"+signature);
Object proceed = jp.proceed();//执行方法
System.out.println("环绕后~~~");
System.out.println(proceed);
}
}
- 实体类
public class Test1 {
public void Test1(){
System.out.println("正在执行方法~");
}
}
- 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" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--方式三:使用注解-->
<bean id="test1" class="com.si.test1.Test1"/>
<bean id="test1Impl" class="com.si.test1.Test1Impl"/>
<!--开启注解支持! JDK(默认是 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
</beans>
- 测试
public class MyTest1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Test1.xml");
Test1 test1 = (Test1) context.getBean("test1");
test1.Test1();
}
}
- 结果
十二、声明式事务
12.1 什么是事务
12.1.1 什么是事务?
- 把一组业务当成一个业务来做;要么都成功,要么都失败
- 事务在项目开发的过程中,十分重要,涉及到数据的一致性问题
- 确保完整性和一致性
12.1.2 事务的 ACID 原则
- 原子性(atomicity):
- 事务都是原子性的操作,有一系列动作完成,事务的原子性确保动作要么全部完成,要么完全不起作用
- 一致性(consistency)
- 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规划的一致性状态中
- 隔离性(isolation)
- 可能有多个失误会同时处理相同的数据,因此每个事物都应该与其他事务隔离开来,放置数据损坏
- 持久性(durability)
- 事物一旦完成,无论系统发生错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化储存器中
12.2 Spring 中的事务管理
12.2.1 声明式事务
- 一般状态下比编程式事务好用
- 将事务管理代码从业务中分离出来,以声明的方式来实现事务管理
- 将事务管理作为横切关注点,通过 AOP 方法模块化。Spring 通过Spring AOP框架支持声明式事务
12.2.2 编程式事务
- 将事务管理的代码嵌入到业务方法中来控制事务的提交和回滚
- 缺点:必须每个事务操作业务逻辑包含额外的事务管理代码
12.2.3 配置事务
- 导入约束:tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
- JDBC 事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
- 配置好事务管理器后配置事务通知
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给那些方法配置事务-->
<!--配置事务的传播特性: new -->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
12.3 配置AOP,导入 AOP 的头文件
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.si.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
12.4 事务的传播特性
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。Spring 支持7种事务的传播行为(默认第一种):
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作。
总结:之前没有进行系统的总结,觉得自己遗漏的东西还是比较多的。通过系统的学习,发现 Spring 并没有想象中的难学,只是东西有点多,需要进行慢慢消化,多上手进行实践!!! 多敲代码