Spring自学(3)

1、使用JavaConfig实现配置

Spring自学(3)_xml

实体类

User.java

package pojo;

import org.springframework.beans.factory.annotation.Value;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 20:46
 * FileName: User
 * Description:
 */
//这里这个注解的意思,就是说名这个类被Spring接管了,注册到了容器中。
public class User {
private String name;

    public String getName() {
        return name;
    }

    @Value("caiwei")//属性注入值。
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置类

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import pojo.User;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 20:52
 * FileName: MyConfig
 * Description:
 */
@Configuration
@ComponentScan("pojo")
@Import(MyConfig2.class)
//这个也会Spring容器托管,注册到容器中,因为他本来就是一个Component,
// Configuration代表这是一个配置类,就和我们之前看的beans.xml
public class MyConfig {

    //注册一个bean .就相当于我们之前写的一个bean标签这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的cLass属性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的对象!
    }
}

测试类

import config.MyConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.User;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 20:56
 * FileName: MyTest
 * Description:
 */
public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context= new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

2、上周内容回顾

...

3、静态代理模式

Spring自学(3)_xml_02

Spring自学(3)_spring_03

Spring自学(3)_java_04

接口

package demo01;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:34
 * FileName: Rent
 * Description:
 */
public interface Rent {
    public void rent();
}

真实角色

package demo01;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:35
 * FileName: LandLord
 * Description:
 */
public class LandLord implements Rent{

    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

代理角色

package demo01;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:39
 * FileName: Proxy
 * Description:
 */
public class Proxy implements Rent{
    private LandLord host;

    public Proxy() {
    }

    public Proxy(LandLord host) {
        this.host = host;
    }

    @Override
    public void rent() {
        seeHouse();
        host.rent();
        signContract();
        fare();
    }

    public void seeHouse(){
        System.out.println("中介带你看房");
    }
    public void signContract(){
        System.out.println("签租赁合同");
    }
    public void fare(){
        System.out.println("收中介费");
    }
}

客户端访问角色

package demo01;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:36
 * FileName: Cilent
 * Description:
 */
public class Client {
    public static void main(String[] args) {
        //房东要租房子
        LandLord landLord = new LandLord();
        //代理,中介帮房东租房子,但是呢?代理角一殷会有一些附属操作!
        Proxy proxy = new Proxy(landLord);
        //你不用面对房东,直接找中介租房即可!
        proxy.rent();
    }
}

4、静态代理再理解

Spring自学(3)_Spring自学_05

接口

package demo02;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:53
 * FileName: UserService
 * Description:
 */
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}

真实角色

package demo02;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:53
 * FileName: UserServiceImpl
 * Description:
 */
//真实对象
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 query() {
        System.out.println("查询了一个用户");
    }
}

代理角色

package demo02;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:57
 * FileName: UserServiceProxy
 * Description:
 */
public class UserServiceProxy implements UserService {
    private UserServiceImpl userservice;

    public void setUserservice(UserServiceImpl userservice) {
        this.userservice = userservice;
    }

    @Override
    public void add() {
        log("add");
        userservice.add();
    }

    @Override
    public void delete() {
        log("delete");
        userservice.delete();
    }

    @Override
    public void update() {
        log("update");
        userservice.update();
    }

    @Override
    public void query() {
        log("query");
        userservice.query();
    }

    //日志方法
    public void log(String msg){
        System.out.println("[Debug]使用了"+msg+"方法");
    }
}

客户端访问角色

package demo02;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:55
 * FileName: Cilent
 * Description:
 */
public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();

        UserServiceProxy userServiceProxy = new UserServiceProxy();
        userServiceProxy.setUserservice(userService);
        userServiceProxy.add();
    }
}

5、动态代理详解

Spring自学(3)_ide_06

Spring自学(3)_ide_07

demo03.Rent.java

package demo03;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/17 21:34
 * FileName: Rent
 * Description:
 */
public interface Rent {
    public void rent();
}

demo03.Host.java

package demo03;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 7:39
 * FileName: Host
 * Description:
 */
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要租房!");
    }
}

demo03.ProxyInvocationHandler.java

package demo03;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 7:44
 * FileName: ProxyInvocationHandler
 * Description:
 */
//等我们会用这个类,自动生成代理类!
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);
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse();
        //动态代理的本质,就是使用反射机制实现!
        Object result = method.invoke(rent, args);
        fare();
        return result;
    }

    public void seeHouse(){
        System.out.println("中介带你看房子");
    }

    public void fare(){
        System.out.println("收中介费");
    }
}

demo03.Client.java

package demo03;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 7:53
 * FileName: Client
 * Description:
 */
public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();

        //代理角色:现在没有
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象!
        proxyInvocationHandler.setRent(host);
        //这里的proxy就是动态生成的,我们并没有写
        Rent proxy = (Rent) proxyInvocationHandler.getProxy();
        proxy.rent();
    }
}

demo04.ProxyInocationHandler.java

package demo04;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:04
 * FileName: ProxyInocationHandler
 * Description:
 */
public class ProxyInocationHandler 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 {
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }
}

demo04.Client.java

package demo04;

import demo02.UserService;
import demo02.UserServiceImpl;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:09
 * FileName: Client
 * Description:
 */
public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色不存在
        ProxyInocationHandler proxyInocationHandler = new ProxyInocationHandler();

        //设置要代理的对象
        proxyInocationHandler.setTarget(userService);
        //动态生成代理类
        UserService proxy = (UserService) proxyInocationHandler.getProxy();

        proxy.delete();
    }
}

6、AOP实现方式—

Spring自学(3)_spring_08

Spring自学(3)_Spring自学_09

Spring自学(3)_spring_10

Spring自学(3)_ide_11

Spring自学(3)_Spring自学_12

service.UserService.java

package service;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:29
 * FileName: service.UserService
 * Description:
 */
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}

service.UserServiceImpl.java

package service;

import service.UserService;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:30
 * FileName: service.UserServiceImpl
 * Description:
 */
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.java

package log;

import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:34
 * FileName: Log
 * Description:
 */
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()+"被执行了");
    }
}

log.AfterLog.java

package log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:39
 * FileName: AfterLog
 * Description:
 */
public class AfterLog implements AfterReturningAdvice {
    //o;返回值
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
    }
}

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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:annotation-config/>

<!--    注册bean-->
    <bean id="userserviceimpl" class="service.UserServiceImpl"/>
    <bean id="log" class="log.Log"/>
    <bean id="afterlog" class="log.AfterLog"/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <aop:config>
        <!--切入点: expression:表达式,execution(要执行的位置!* * * * *) -->
        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>

        <!--执行环绕培加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

MyTest.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 8:55
 * FileName: MyTest
 * Description:
 */
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        动态代理代理的是接口
        UserService userserviceimpl = (UserService) context.getBean("userserviceimpl");
        userserviceimpl.add();
    }
}

7、AOP实现方式二

Spring自学(3)_spring_13

diy.DiyPointCut.java

package diy;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 9:11
 * FileName: DiyPointCut
 * Description:
 */
public class DiyPointCut {
    public void before(){
        System.out.println("===方法执行前===");
    }

    public void after(){
        System.out.println("===方法执行后===");
    }
}

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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:annotation-config/>

    <!--    注册bean-->
    <bean id="userserviceimpl" class="service.UserServiceImpl"/>
    <bean id="log" class="log.Log"/>
    <bean id="afterlog" class="log.AfterLog"/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <!--    <aop:config>-->
    <!--        &lt;!&ndash;切入点: expression:表达式,execution(要执行的位置!* * * * *) &ndash;&gt;-->
    <!--        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>-->

    <!--        &lt;!&ndash;执行环绕培加!&ndash;&gt;-->
    <!--        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>-->
    <!--        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>-->
    <!--    </aop:config>-->

    <!--方式二:自定义类-->
    <bean id="diy" class="diy.DiyPointCut"/>

    <aop:config>
        <!--自定义切面, ref要引用的类-->
        <aop:aspect ref="diy">
            <!--            切入点-->
            <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

8、注解实现AOP

diy.AnnotationPointCut.java

package diy;

//方式三:使用注解方式实现AOP

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;

/**
 * Author: Gu Jiakai
 * Date: 2021/9/18 9:25
 * FileName: AnnotationPointCut
 * Description:
 */
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===方法执行前===");
    }

    @After("execution(* service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===方法执行后===");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
    @Around("execution(* service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");

        //执行方法
        Object proceed = jp.proceed();

        System.out.println("环绕后");
    }
}

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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:annotation-config/>

    <!--    注册bean-->
    <bean id="userserviceimpl" class="service.UserServiceImpl"/>
    <bean id="log" class="log.Log"/>
    <bean id="afterlog" class="log.AfterLog"/>

    <!--方式三-->
    <bean id="annotationPointCut" class="diy.AnnotationPointCut"/>
<!--    开启注解支持。JDK(默认proxy-target-cLass="false") cdlib (proxy-target-class="true" ) -->
    <aop:aspectj-autoproxy/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <!--    <aop:config>-->
    <!--        &lt;!&ndash;切入点: expression:表达式,execution(要执行的位置!* * * * *) &ndash;&gt;-->
    <!--        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>-->

    <!--        &lt;!&ndash;执行环绕培加!&ndash;&gt;-->
    <!--        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>-->
    <!--        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>-->
    <!--    </aop:config>-->

    <!--方式二:自定义类-->
<!--    <bean id="diy" class="diy.DiyPointCut"/>-->

<!--    <aop:config>-->
<!--        &lt;!&ndash;自定义切面, ref要引用的类&ndash;&gt;-->
<!--        <aop:aspect ref="diy">-->
<!--            &lt;!&ndash;            切入点&ndash;&gt;-->
<!--            <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>-->
<!--            &lt;!&ndash;通知&ndash;&gt;-->
<!--            <aop:before method="before" pointcut-ref="point"/>-->
<!--            <aop:after method="after" pointcut-ref="point"/>-->
<!--        </aop:aspect>-->
<!--    </aop:config>-->
</beans>