1.Spring

1.Spring

简介:

  • 2002,首次推出了Spring框架的雏形:interface21框架
  • 2004年3月24发布了1.0正式版
  • Rod Johnson,SpringFramework创始人.(悉尼大学音乐学博士)

1.IOC导论

先看一下在没有使用spring框架时,我们是怎样开发的.这里使用一个dao层和一个service层做示范,Dao层中有一个userDao类,提供了一个获取用户信息的方法.
在service层中调用Dao层,用户看不见Dao层的操作.

1.userDao接口
package com.kingkiller.dao;
public interface UserDao {
    void getUser();
}
2.UserDaoImpl实现类
package com.kingkiller.dao;
public class UserDaoImpl implements UserDao {
    public void getUser(){
        System.out.println("默认获取用户的数据");
    }
}
3.UserService业务接口
package com.kingkiller.service;
public interface UserService {
    void getUser();
}
4.UserServiceImpl业务实现类
package com.kingkiller.service;
import com.kingkiller.dao.UserDao;
import com.kingkiller.dao.UserDaoImpl;
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    public void getUser(){
        userDao.getUser();
    }
}
5.创建测试类进行测试
	@Test
    public void test3(){
        //用户实际调用的是业务层,dao层他们不需要接触
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码是十分大,修改一次的代价成本十分昂贵

例如,我们再新建一个MysqlDaoImpl,用户想调用Mysql中的数据,那我们就需要修改UserServiceImpl中的代码将UserDao userDao = new UserDaoImpl();改成UserDao MysqlDaoImpl();[耦合性很高]

我们使用一个Set接口实现,已经发生了革命性的变化

为UserServiceImpl中的userDao添加set方法

private UserDao userDao = new UserDaoImpl();
//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
	this.userDao = userDao;
}

在测试类中就可以进行调用不同的UserDao的实现类

    @Test
    public void test(){
        //用户实际调用的是业务层,dao层他们不需要接触
        UserService userService = new UserServiceImpl();
        ((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
        userService.getUser();
    }

之间程序是主动创建对象,控制权在程序员手上

使用了set注入后,程序不在具有主动性,而是被动接收对象

这种思想从本质上解决了问题,我们程序员不用再去管理对象的创建了.系统的耦合性大大降低,可以更加的专注在业务的实现上!这是IOC的原型!

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法

在这里插入图片描述

个人理解控制反转就是:获得依赖的对象反转了

IoC是Spring框架的核心内容,使用了多种方式完美的实现了IoC.可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC

Spring容器在初始化时先读取配置文件跟就配置文件的或元数据创建与组织对象存入容器中,程序使用时再从IoC取出需要的对象

最后所谓的IoC一句话搞定就是:对象由Spring来创建管理,装配

2.Spring配置

2.1、别名
<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象 -->
<alias name="user" alias="userNew"/>
2.2、Bean的配置
<bean id="user" class="com.kingkiller.pojo.User" name="user2 u2,u3;u4">
	<property name="name" value="kingkiller"/>
<bean>
2.3、import

这个import一般用于团队开发使用,他可以将多个配置文件导入合并为一个假设,现在项目中有多人开发,每个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以使用import将所有人的beans.xml合并为一个

<import resource="beans.xml"/>
<import resource="beans2.xml"/>

3.SpringIoC入门

1.创建一个Maven项目,并导入Spring的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.kingkiller</groupId>
    <artifactId>spring-study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
    </dependencies>
</project>
2.创建User类

在com.kingkiller.pojo类中创建User类

package com.kingkiller.pojo;
public class User {
    private String name;
    private int age;
}

注意:这里需要自己补齐成员变量的get和set方法,以及重写toString方法

3.创建配置文件

在resource中创建applicationContext.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">
    <bean id="user" class="com.kingkiller.pojo.User"/>
</beans>
4.创建测试类进行单元测试
    @Test
    public void test2(){
        //获取ApplicationContext
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //需要什么就get什么
        User user = context.getBean("user", User.class);
        System.out.println(user);
    }

4.依赖注入

3.1 构造器注入
package x.y;
public class ThingOne {
    public ThingOne(ThingTwo thingTwo, ThingThree thingThree) {
        // ...
    }
}
<beans>
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg ref="beanTwo"/>
        <constructor-arg ref="beanThree"/>
    </bean>
    <bean id="beanTwo" class="x.y.ThingTwo"/>
    <bean id="beanThree" class="x.y.ThingThree"/>
</beans>
3.2 Set方式注入[重点]

依赖注入:set注入

​ 依赖:bean对象的创建依赖于容器!

​ 注入:bean对象中的所有属性,由容器来注入

首先建立Address类

package com.kingkiller.pojo;
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 + '\'' +
                '}';
    }
}

再建立Student类

package com.kingkiller.pojo;
import java.util.*;
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobby;
    private Map<String,String> card;
    private Set<String> games;
    private String girlfriend;
    private Properties info;

注:自己补全成员变量的get和set方法,还有重写toString方法,这里因为篇幅的原因就不展示了

编写配置文件applicationContext.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="address" class="com.kingkiller.pojo.Address"/>
    <bean id="student" class="com.kingkiller.pojo.Student">
        <!-- 第一种普通值注入 -->
        <property name="name" value="kingkiller"/>
        <!-- 第二种,Bean注入 -->
        <property name="address" ref="address"/>
        <!-- 数组注入,ref -->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国演义</value>
                <value>水浒传</value>
                <value>西游记</value>
            </array>
        </property>
        <!-- list注入 -->
        <property name="hobby">
            <list>
                <value>踢球</value>
                <value>看电影</value>
            </list>
        </property>
        <!-- map注入 -->
        <property name="card">
            <map>
                <entry key="身份证" value="12345678"/>
                <entry key="银行卡" value="12345678"/>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>
        <!-- NULL -->
        <property name="girlfriend">
            <null/>
        </property>
        <!-- Properties -->
        <property name="info">
            <props>
                <prop key="username">kingkiller</prop>
            </props>
        </property>
    </bean>
</beans>

上面就是set方式进行注入

之后建立测试类进行单元测试

import com.kingkiller.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = context.getBean("student", Student.class);
        System.out.println(student.toString());
    }
}
3.3拓展方式注入

我们可以使用p命令空间和c命令空间进行注入:

新建一个User类

package com.kingkiller.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 +
                '}';
    }
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public User(){}
}

编写配置文件userbeans.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命名空间注入,可以直接注入属性的值 -->
    <bean id="user" class="com.kingkiller.pojo.User" p:name="king" p:age="18"/>
    <bean id="user2" class="com.kingkiller.pojo.User" c:name="queen" c:age="20"/>
</beans>

编写测试类进行单元测试

@Test
public void test2(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user);
        Object user2 = context.getBean("user2");
        System.out.println(user2);
    }

注意点:p命名空间不能直接使用,需要导入约束xmlns:p=“http://www.springframework.org/schema/p” xmlns:c=“http://www.springframework.org/schema/c”

3.4 bean的作用域
ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

1.singleton:单例模式(spring的默认机制)

<bean id="user2" class="com.kingkiller.pojo.User" c:name="queen" c:age="20" scope="singleton"/>

2.prototype:原型模式,每次从spring容器中get的时候,都会产生一个新的对象

3.其余的request,session,application这些只能在web开发中使用到!

5.Bean的自动装配

概述
  • 自动装配是Spring满足Bean依赖的一种方式

  • Spring会在上下文中自动寻找,并自动给bean装配属性

在spring中有三种装配方式

  1. 在xml中显示配置

  2. 在java中显示配置

  3. 隐式的自动装配[重点]

4.1 测试

环境搭建:一个人有两个宠物

建立Cat,Dog,Person类

public class Dog {
    public void shout(){
        System.out.println("wang~");
    }
}
public class Cat {
    public void shout(){
        System.out.println("miao~");
    }
}
public class Person {
    private String name;
    private Cat cat;
    private Dog dog;
}

Person类中自己添加get和set方法,重写toString方法

4.2ByName自动装配
<?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.kingkiller.pojo.Cat"/>
    <bean id="dog" class="com.kingkiller.pojo.Dog"/>
    <!-- 会自动在容器上下文查找,和自己对象set方法后面的值对应的beanid! -->
    <bean id="people" class="com.kingkiller.pojo.Person" autowire="byName">
        <property name="name" value="king"/>
    </bean>
</beans>

但需要注意,自已定义的属性变量所对应的类的beanid必须一致

4.3ByType自动装配
  <bean id="people" class="com.kingkiller.pojo.Person" autowire="byType">
        <property name="name" value="king"/>
    </bean>

但需要注意,bean中无法有两个相同的类!

小结:

  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法一致!
  • byType的时候,需要保证所有bean的class唯一,并且这个需要和自动注入的属性一致!
4.4使用注解实现自动装配

jdk1.5支持的注解,Spring2.5就支持注解

使用注解须知:

1.导入约束

2.配置注解的支持

<context:annotation-config/>

@Autowired:

直接在属性上使用即可,也可以在set方式上使用!

使用Autowired我们可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname!

科普:

@Nullable //字段标记了这个注解,说明这个字段可以为null
public @interface Autowired{
	boolean required() default true;
}

如果显示定义了Autowired的required属性为false,说明这个对象可以为空,否则不允许为空

@Qualifier:

配合@Autowired注解使用.当有多个对象实例时,可以设置使用哪一个对象实例

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Qualifier {
	String value() default "";
}

设置value值即可指定对象

public class Person {
    private String name;
    @Autowired
    @Qualifier("cat1")
    private Cat cat;
    @Autowired
    private Dog dog;
}

@Resource:

是javax.annotation包下的注解,也可与使用这个注解进行自动装配,可以对该注解的name属性进行赋值来选择注入哪个对象

public class Person {
    private String name;
    @Autowired
    @Qualifier("cat1")
    private Cat cat;
    @Resource(name = "dog2")
    private Dog dog;
}

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上

  • @Autowired通过byType的方式实现,而且必须要求这个对象存在

  • @Resource默认通过byName实现,如果找不到byType实现,如果两个都找不到就报错

    6.使用注解开发

    在spring4之后,要使用注解开发,就必须保证aop的包导入了

    在使用注解需要导入context约束,增加注解的支持

    <?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:component-scan base-package="com.kingkiller.pojo"/>
        <!-- 开启注解支持 -->
        <context:annotation-config/>
    </beans>
    
    1.bean

    在类上标记@Component注解就可以自动实习bean的注入,不需要再去xml中进行bean的配置

    @Component
    
    2.属性如何注入
    @Component
    public class User {
        //相当于<property name="name" value="king"/>
        @Value("king")
        public String name;
    }
    

    也可以将@Value写在set方法中

    @Value("king")
    public void setName(){
    	this.name = name;
    }
    
    3.衍生的注解

    __@Component__有几个衍生的注解,我们在web开发中,会按照mvc三层架构分层!

    • dao [@Repository] (注意:SpringBoot中所学到的@Mapper注解是mybatis提供的,不是spring)

    • service [@Service]

    • controller [@Controller]

      这四个注解其实功能都是一样的,都是代表将某个类注册到spring中,装配bean(对内)

4.自动装配
public class Person {
    private String name;
    @Autowired
    @Qualifier("cat1")
    private Cat cat;
    @Resource(name = "dog2")
    private Dog dog;
}
5.作用域
@Component
@Scope("prototype")
public class User {
    //相当于<property name="name" value="king"/>
    @Value("king")
    public String name;
}
6.xml与注解:
  • xml更加万能,适用于任何场合,维护简单

  • 注解不是自己的类无法使用,维护相对复杂

xml与注解的最佳实践:

  • xml用来管理bean
  • 注解只负责属性的注入

6.使用java的方式配置spring

我们现在要完全不使用Spring的xml配置,全权交给java来做

javaConfig是Spring的一个子项目,在Spring4之后,它成了一个核心功能

1.新建一个pojo类
package com.kingkiller.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
    private String name;
    public String getName() {
        return name;
    }
    @Value("king")
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
2.创建MyConfig
package com.kingkiller.config;
import com.kingkiller.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
 * 这个也会被spring容器托管,注册到容器中,因为它本来就是一个@Component
 * @COnfiguration 代表这是一个配置类
 */
@Configuration
@ComponentScan("com.kingkiller.pojo")//开启包扫描
@Import(MyConfig2.class)//导入其他配置类
public class MyConfig {
    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User();
    }
}
3.创建测试类
import com.kingkiller.config.MyConfig;
import com.kingkiller.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
	@Test
    public  void test() {
        //如果完全使用了配置类方法去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("user", User.class);
        System.out.println(user.getName());
    }
}
4.原理分析

进入@Configuration源码,可以发现它本身也是一个Component

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
	@AliasFor(annotation = Component.class)
	String value() default "";
	boolean proxyBeanMethods() default true;
}

这种java的配置方式,在SpringBoot中随处可见!

进入springboot启动类注解@SpringBootApplication的源码

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration		//---------也是Configuration
@EnableAutoConfiguration		//---------这个是自动配置
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {...}

继续进入@SpringBootConfiguration的源码,发现它本身就是一个Configuration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {...}
  • Spring Boot

    • 一个快速开发脚手架
    • 基于SpringBoot可以快速开发单个微服务
    • 约定大于配置
  • SpringCloud

    • SpringCloud是基于SpringBoot实现的

弊端:发展太久之后,违背了原来的理念!配置十分繁琐,“配置地狱”!

在这里插入图片描述

​ 构建一切 合作一切 连接一切

7.代理模式

为什么要学习代理模式? 因为这就是SpringAOP的底层 [SpringAOP 和 SpringMVC是面试的重点]

代理模式的分类:

  • 静态代理
  • 动态代理
7.1静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的对象
  • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理对象的人

代码实现步骤:

  1. 接口

    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

    public class Host implements Rent {
        @Override
        public void rent() {
            System.out.println("房东要出租房子");
        }
    }
    
  3. 代理角色

    public class Proxy implements Rent {
        private Host host;
        public Proxy(){}
        public Proxy(Host host) {
            this.host = host;
        }
        @Override
        public void rent() {
            seeHose();
            host.rent();
            hetong();
            fee();
        }
        //看房
        public void seeHose(){
            System.out.println("中介带你看房");
        }
        //收中介费
        public void fee(){
            System.out.println("收中介费");
        }
        //签合同
        public void hetong(){
            System.out.println("签租赁合同");
        }
    }
    
    
  4. 客户端访问代理角色

    public class Client {
        public static void main(String[] args) {
            Host host = new Host();
            Proxy proxy = new Proxy(host);
            proxy.rent();
        }
    }
    

代理模式的好处:

  • 可以使真实角色的操作更加纯粹
  • 公共业务就交给了代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理

缺点:

  • 一个真实角色就会产生一个代理角色;代码量会翻倍-开发效率会变低
7.2加深理解

建议去看一下23种设计模式和面向对象七大原则是

代码实现:

1.接口

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void  select();
}

2.实现类

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("查询了一个数据");
    }

上面是一个正常的service业务层,但现在如果想添加一个日志功能,即在每次更新数据库时都能输出这次的操作是什么并写入log中,我们可以通过更改实现类中的每一个方法去完成,但是操作会过于繁琐,而且有损毁原始代码的风险,这个时候可以使用静态代理的方式

3.代理对象

public class UserServiceProxy implements UserService {
    private UserServiceImpl userService;
    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
    @Override
    public void add() {
        log("add");
        userService.add();
    }
    ... ...	
    //日志方法
    public void log(String msg){
        System.out.println("使用了"+msg+"方法");
    }
}

注:还有一些重写接口中的方法没有写出来,自行补齐

4.测试类

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);
        proxy.add();
    }
}

这样就可以很简单的实现更改原有需求

在这里插入图片描述

7.3动态代理
  • 动态代理和静态代理角色一样
  • 动态代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理.基于类的动态代理
    • 基于接口 – JDK代理 []
    • 基于类 – cglib
    • java字节码实现 – javassist

需要了解两个类:Proxy,InvocationHandler:调用处理程序

代码的实现:

1.接口(和上面Rent接口一样,略)

2.实现类(和上面Host实现类一样,略)

3.自定义动态代理类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//等会我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Rent rent;
    public void setRent(Rent rent) {
        this.rent = rent;
    }
    //生成代理对象
    public Object getProxy(){
        //查询字典
        //static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
        //                                类加载器,可以是本类,    要代理的接口,  Handler类,本类继承了Handler,可以使用本类
        //          返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }
    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse();
        //翻阅字典 Object invoke(Object obj, Object... args)
        //          对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。
        //动态代理的本质,就是使用反射的机制实现
        Object result = method.invoke(rent, args);
        fee();
        return null;
    }
    public void seeHouse(){
        System.out.println("看房");
    }
    public void fee(){
        System.out.println("收费");
    }
}

4.测试类(客户类)

public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理角色
        ProxyInvocationHandler prh = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象
        prh.setRent(host);
        Rent proxy = (Rent)prh.getProxy();
        proxy.rent();
    }
}

我们可以将上面的代码改动的更加灵活

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
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);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        method.invoke(target, args);
        return null;
    }
}

5.更改后的测试类

public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色,不存在,去创建一个
        ProxyInvocationHandler prh = new ProxyInvocationHandler();
        prh.setTarget(userService);//设置要代理的对象
        //动态生产代理
        UserService proxy = (UserService)prh.getProxy();
        proxy.play();
    }
}

动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关心一些公共的业务
  • 公共也就交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类代理的是一个接口,一般就是对应一类业务
  • 一个动态代理类可以代理多个类,只要实现接口即可

MyBatis底层其实也是基于代理模式设计的

在这里插入图片描述
在这里插入图片描述

8.AOP

1.什么是AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型.利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率

在这里插入图片描述

2.Aop在Spring中的作用

提供声明事务:允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能,即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点.如日志安全,缓存事务等…

  • 切面(ASPECT):横切关注点被模块化的特殊对象,即它是一个类

  • 通知(Advice):切面必须要完成的工作.即,它是类中的一个方法

  • 目标(Target):被通知对象.

  • 代理(Proxy):向对象应用通知之后创建的对象

  • 切入点(PointCut):切面通知执行的"地点"的定义

  • 连接点(JointPonit):与切入点匹配的执行点

在这里插入图片描述

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice
在这里插入图片描述
即Aop在不改变原有代码的情况下,去增加新的功能

3.使用Spring实现AOP

[重点]使用AOP织入

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

方式一:使用Spring的API接口[主要是SpringAPI接口实现]

1.新建接口UserService和实现类UserServiceImpl

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}
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("查询了一个数据");
    }
}

2.新建Log日志功能

import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

3.配置applicationContext.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 http://www.springframework.org/schema/aop/spring-aop.xsd ">
    <!-- 配置bean -->
    <bean id="userService" class="com.kingkiller.service.UserServiceImpl"/>
    <bean id="log" class="com.kingkiller.log.Log"/>
    <bean id="afterLog" class="com.kingkiller.log.AfterLog"/>
    <!-- 方式一 -->
    <!-- 配置aop:需要导入aop的配置 -->
    <aop:config>
        <!-- 切入点 execution(要执行的位置! * 类的全路径名 .*表示全方法 (..)表示各种参数) -->
        <aop:pointcut id="pointcut" expression="execution(* com.kingkiller.service.UserServiceImpl.*(..))"/>
        <!-- 执行环绕增加,表示要将哪一个类切入到哪里 -->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

注意:需要导入头文件xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation=http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd ">

4.测试类进行单元测试

public class MyTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService =  context.getBean("userService",UserService.class);
        userService.add();
    }
}

方式二:自定义类来实现AOP[主要是切面实现]

1.创建自定义切面类

public class DiyPointcut {
    public void before(){
        System.out.println("=====方法执行前=====");
    }
    public void after(){
        System.out.println("=====方法执行前=====");
    }
}

2.配置applicationContext.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 http://www.springframework.org/schema/aop/spring-aop.xsd ">
    <!-- 配置bean -->
    <bean id="userService" class="com.kingkiller.service.UserServiceImpl"/>
    <bean id="log" class="com.kingkiller.log.Log"/>
    <bean id="afterLog" class="com.kingkiller.log.AfterLog"/>
    <!-- 方式二 -->
    <bean id="diy" class="com.kingkiller.diy.DiyPointcut"/>
    <aop:config>
        <!-- 自定义切面,ref:要引入的类 -->
        <aop:aspect ref="diy">
            <!-- 切入点(也就是类) -->
            <aop:pointcut id="point" expression="execution(* com.kingkiller.service.UserServiceImpl.*(..))"/>
            <!-- 通知(也就是类中的方法) -->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

3.测试类进行测试

public class MyTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService =  context.getBean("userService",UserService.class);
        userService.add();
    }
}

方式三:使用注解实现

1.建立自定义切面类

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//使用注解方式实现aop
@Aspect //标注这个类是一个切面
public class AnnotationPointcut {
    @Before("execution(* com.kingkiller.service..UserServiceImpl.*(..))")
    public void before(){
        System.out.println("---方法执行前---");
    }
}

2.配置applicationContext.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 http://www.springframework.org/schema/aop/spring-aop.xsd ">
    <!-- 配置bean -->
    <bean id="userService" class="com.kingkiller.service.UserServiceImpl"/>
    <bean id="log" class="com.kingkiller.log.Log"/>
    <bean id="afterLog" class="com.kingkiller.log.AfterLog"/>
    <!-- 方式三 -->
    <bean id="annotationPointcut" class="com.kingkiller.diy.AnnotationPointcut"/>
    <!--开启注解支持 -->
    <aop:aspectj-autoproxy/>
</beans>

3.测试类进行测试

public class MyTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService =  context.getBean("userService",UserService.class);
        userService.add();
    }
}
@Before("execution(* com.kingkiller.service..UserServiceImpl.*(..))")
public void before(){
    System.out.println("---方法执行前---");
}

}


2.配置applicationContext.xml

```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 http://www.springframework.org/schema/aop/spring-aop.xsd ">
    <!-- 配置bean -->
    <bean id="userService" class="com.kingkiller.service.UserServiceImpl"/>
    <bean id="log" class="com.kingkiller.log.Log"/>
    <bean id="afterLog" class="com.kingkiller.log.AfterLog"/>
    <!-- 方式三 -->
    <bean id="annotationPointcut" class="com.kingkiller.diy.AnnotationPointcut"/>
    <!--开启注解支持 -->
    <aop:aspectj-autoproxy/>
</beans>

3.测试类进行测试

public class MyTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService =  context.getBean("userService",UserService.class);
        userService.add();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值