Spring系列(二)自动装配和AOP

Spring系列(二)自动装配和AOP

1. 自动装填

自动装配:

  • byName:会自动在容器上下文中查找,和自己set方法后面的值对应的bean id
  • byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
<bean id="people" class="top.qwwq.pojo.People" autowire="byName">
    <property name="name" value="EnderKC"/>
    <property name="dog" ref="dog"/>
    <property name="cat" ref="cat"/>
</bean>

自动装配注解:

  • @Autowired 自动装配 Spring的包
  • @Resource 自动装配 javax的包
  • @Nullable 允许为null

2. 注解开发

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

111

使用注解需要导入注解的支持
Spring官网

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>
  • @Component 放在类上,说明这个类被Spring管理了 等价于
    <bean id="user" class="top.qwwq.pojo.User"/>
    
  • @Value 给属性注入值,等价于 👇
    <bean id="user" class="top.qwwq.pojo.User">
        <property name="name" value="EnerKC"/>
    </bean>
    
  • @Scope 设置作用域
  1. bean

  2. 属性如何注入

    @Component
    public class User {
        @Value("EnderKC")
        public String name;
    }
    
  3. 衍生的注解

    • @Component 有几个衍生注解,我们在web开发中,会按照MVC三层架构分层!
      • dao 【@Repository】
      • service 【@Service】
      • controller 【@Controller】
      这四个注解的功能一样,都是代表将某个类注册到Spring中,装配Bean
  4. 小结

    XML与注解

    • xml更加万能,方便维护
    • 不是自己的类引用不了,维护相对复杂

    XML与注解最佳实践:

    • xml用来管理bean
    • 直接只负责完成属性的注入
    • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,要开启注解支持

3. 使用JAVA的方式配置

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

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

MyConfig.java 配置类

@Configuration // 这个也会被Spring容器托管,注册到容器中 @Configuration 本身是一个 @Component
@Import(MyConfig2.class)
public class MyConfig {
    // 注册一个bean,就相当于我们之前写的一个bean标签
    // 这个方法的名字就相当于bean标签中的id属性
    // 这个方法的返回值就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User();
    }
}

User.java 实体类

//@Component // 说明这个类被Spring接管 注册到了容器中
@Data
public class User {
    @Value("EnderKC")  // 注入值
    private String name;
}

MyTest.java 测试类

public class MyTest {
    @Test
    public void test1(){
        // 如果完全使用了配置类去做,我们就只能通过ApplicationContext上下文来获取容器,通过配置类的class对象加载类
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("getUser", User.class);
        System.out.println(user);
    }
}

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

4. 代理模式

为什么要学习代理模式?

因为这就是SpringAop的底层 【SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

代理模式

4.1 静态代理

角色分析

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

代码步骤:

  • 接口
    // 租房的接口
    public interface Rent {
        void rent();
    }
    
  • 真实角色
    // 房东
    public class Host implements Rent{
        @Override
        public void rent() {
            System.out.println("房东要出租房子");
        }
    }
    
  • 代理角色
    public class Proxy implements Rent{
        private Host host;
    
        @Override
        public void rent() {
            host.rent();
        }
        // 看房
        public void seeHouse(){
            System.out.println("中介带你看房");
        }
        // 收中介费
        public void fare(){
            System.out.println("中介收中介费");
        }
        // 签合同
        public void hetong(){
            System.out.println("中介签合同");
        }
    }
    
  • 客户端访问代理角色
    public class Client {
        public static void main(String[] args) {
            // 房东想租房子
            Host host = new Host();
            // 代理,中介帮助房东租房子,代理一般会有一些附属操作。
            Proxy proxy = new Proxy(host);
            // 你不用找房东,直接找中介就行
            proxy.rent();
        }
    }
    

代理模式的好处:

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

缺点:

  • 一个真是角色,就要产生一个代理角色,代码量会翻倍,开发效率会低

4.2 加深理解

聊聊AOP

AOP

4.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理类是动态生成的,不是我们直接写好的!
  • 动态代理分为两大类:
    • 基于接口的动态代理
      • JDK的动态代理
    • 基于类的动态代理
      • cglib
    • Java字节码实现 JavaAssist

需要了解两个类: Proxy InvocationHandler

万能动态代理类实现代码:

// 我们会用这个类自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {

    // 被代理的接口
    private Object target;

    public void setTarget(Rent 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 {

        // 动态代理的本质,就是使用反射机制实现!
        return method.invoke(target, args);
    }

}

客户使用代理 代码实例:

public class Client {
    public static void main(String[] args) {
        // 真实角色
        Host host = new Host();
        // 代理角色: 现在没有
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        // 通过程序处理角色来处理我们要调用的接口对象
        pih.setRent(host);

        Rent proxy = (Rent) pih.getProxy();

        proxy.rent();
    }
}

动态代理的好处:

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

5. AOP

5.1 什么是AOP

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

什么是AOP

5.2 AOP在Spring中的作用

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

  • 横切关注点: 跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等 ....
  • 切面 (ASPECT) : 横切关注点 被模块化 的特殊对象。即,它是一个类 【比如说log】
  • 通知 (Advice) :切面必须要完成的工作。即,它是类中的一个方法 【比如说log中的方法】
  • 目标 (Target) : 被通知对象 【一个接口,或者一个方法】
  • 代理 (Proxy) : 向目标对象应用通知之后创建的对象 【生成的代理类】
  • 切入点 (PointCut) : 切面通知 执行的“地点”的定义
  • 连接点 (JointPoint) : 与切入点匹配的执行点

AOP在Spring中的作用

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

Advice

使用AOP织入,需要导入一个依赖包

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

如果我们想写一个日志的功能

方式一:使用Spring的接口

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

    <context:annotation-config/>

<!--注册bean-->
    <bean id="userService" class="top.qwwq.service.UserServiceImpl"/>
    <bean id="log" class="top.qwwq.log.Log"/>
    <bean id="afterLog" class="top.qwwq.log.AfterLog"/>
<!--    方式一:使用原生Spring API接口-->
<!--配置AOP 需要导入aop的约束-->
    <aop:config>
<!--        切入点:需要在那个地方执行  execution 要执行的位置 (*(修饰词) *(返回值) *(类名) *(方法名) *(参数))-->
        <aop:pointcut id="pointcut" expression="execution(* top.qwwq.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>

</beans>

创建包 log service

AfterLog.java

public class AfterLog implements AfterReturningAdvice {
    // returnValue 返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
    }
}

Log.java

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()+"被执行了");
    }
}

UserService.java 接口

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

UserServiceImpl.java

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("查找了一个用户");
    }
}

MyTest.java

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 动态代理代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();

    }
}

方式二:使用自定义类 【没有第一中方法灵活】

新建diy
DiyPointCut.java

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

    <context:annotation-config/>

<!--注册bean-->
    <bean id="userService" class="top.qwwq.service.UserServiceImpl"/>
    <bean id="log" class="top.qwwq.log.Log"/>
    <bean id="afterLog" class="top.qwwq.log.AfterLog"/>
<!--方式二:自定义类-->
    <bean id="diy" class="top.qwwq.diy.DiyPointCut"/>
    <aop:config>
<!--        自定义切面 ref要引用的类-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="pointcut" expression="execution(* top.qwwq.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

</beans>

Test输出

========方法执行前========
增加了一个用户
========方法执行后========

方式三:注解实现AOP

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

    <context:annotation-config/>

<!--注册bean-->
    <bean id="userService" class="top.qwwq.service.UserServiceImpl"/>
    <bean id="log" class="top.qwwq.log.Log"/>
    <bean id="afterLog" class="top.qwwq.log.AfterLog"/>
<!--方式三-->
    <bean id="annotationPointCut" class="top.qwwq.diy.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>

</beans>

AnnotationPointCut.java

package top.qwwq.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect // 标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* top.qwwq.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("========执行方法前===========");

    }
    @After("execution(* top.qwwq.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("========执行方法后===========");
    }
    // 在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* top.qwwq.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) {
        System.out.println("========环绕前=======");
        Signature signature = jp.getSignature(); // 获得签名
        System.out.println(signature);
        // 执行方法
        try {
            jp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

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

    }
}

其他的文件什么都不用改,直接运行就好
MyTest.java

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 动态代理代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

Spring系列(二)自动装配和AOP
http://localhost:8090//archives/D0g4dMcW
作者
EnderKC
发布于
2024年12月23日
许可协议