第84天学习打卡(Spring 使用注解开发 使用Java的方式配置Spring 代理模式 AOP)

8 使用注解开发

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

image-20210517195254342

使用注解需要导入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:annotation-config/>

</beans>

1.bean

2.属性如何注入

package com.kuang.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于 <bean id="user" class="com.kuang.pojo.User"/>
//@Component 组件
@Component
public class User {

    //相当于<property name="name" value="kuangshen"/>

    public String name;
    @Value("kuangshen")
    public void setName(String name){
        this.name = name;
    }

}

3.衍生的注解

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

    • dao【@Repository】
    • service【@Service】
    • controller【@Controller】

    这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean

4.自动装配置

@Autowired: 自动装配通过类型。名字。 如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxxx")-@Nullable  字段标记了这个注解,说明这个字段可以为null
@Resource:自动装配通过名字。类型

5.作用域

package com.kuang.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//等价于 <bean id="user" class="com.kuang.pojo.User"/>
//@Component 组件
@Component
@Scope("prototype")
public class User {

    //相当于<property name="name" value="kuangshen"/>

    public String name;
    @Value("kuangshen")
    public void setName(String name){
        this.name = name;
    }

}

6.小结

xml与注解:

    • xml更加万能,适合于任何场合!维护简单方便
    • 注解 不是自己的类使用不了,维护相对复杂!

xml与注解最佳实践:

    • xml用来管理bean;

    • 注解只负责完成属性的注入;

    • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持。

      指定要扫描的包,这个包下的注解就会生效

<context:component-scan base-package="com.kuang"/>
<context:annotation-config/>

9. 使用Java的方式配置Spring

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

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

image-20210517195407399

实体类:

package com.kuang.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
    private String name;

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

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

配置文件:

package com.kuang.config;

import com.kuang.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代表这是一个配置类,就和我们之前看的beans,xml一样
@Configuration
@ComponentScan("com.kuang.pojo")
@Import(KuangConfig2.class)
public class KuangConfig {

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

测试:

import com.kuang.config.KuangConfig;
import com.kuang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig 上下文来获取容器,通过配置了的class对象加载
    ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
       User getUser = (User) context.getBean("user");
        System.out.println(getUser.getName());
    }
}

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

10 代理模式

为什么要学习代理模式?

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

代理模式:

  • 静态代理

  • 动态代理

image-20210517195451852

10.1静态代理

角色分析:

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

代码步骤:

1.接口

package com.kuang.demo01;

//租房
public interface Rent {
    public void rent();
}

2.真实角色

package com.kuang.demo01;

//房东
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子!");

    }
}

3.代理角色

package com.kuang.demo01;

//组合优于集成原则
public class Proxy {
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }
    public void rent(){
        seeHouse();
        host.rent();
        contract();
        fee();
    }

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

    //签租赁合同
    public void contract(){
        System.out.println("签租赁合同");
    }
    //收中介费
    public void fee(){
        System.out.println("收中介费");
    }
}

4、客户端访问代理角色

package com.kuang.demo01;

public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //代理,中介帮房东租房子,但是,代理角色一般会有一些附属操作
        Proxy proxy = new Proxy(host);

        //你不用面对房东,直接找中介租房即可!
        proxy.rent();

    }
}

代理模式的好处:

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

缺点:

  • 一个真实角色就会产生一个代理角色;代码量会翻倍,开发效率会变低。

10.2 加深理解

代码:对应08-demo02

聊聊AOP

image-20210517195522184

10.3动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的!
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口 ---- JDK动态代理【我们在这里使用】
    • 基于类:cglib
    • java字节码实现:javasist

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

动态代理的好处:

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

11 AOP

11.1 什么是AOP

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

image-20210517195835466

11.2 Aop在Spring中的作用

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

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

image-20210517195907043

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

image-20210517195924842

即AOP在不改变原有代码的情况下,去增加新的功能。

11.3 使用Spring实现AOP

【重点】使用AOP织入,需要导入一个依赖包!

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

<?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.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>
    <!--配置aop:需要导入aop的约束-->
    <aop:config>
    <!--切入点:expression:表达式,execution(要执行的位置!*(修饰词)*(返回值)*(类名)*(方法名)*(参数))-->
         <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

方式1:使用Spring的API接口

applicationContext.xml:【主要SpringAPI接口实现】

<?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="userService" class="com.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>

        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>
    
</beans>

service:

package com.kuang.service;

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

package com.kuang.service;

public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增加了一个用户");

    }

    public void delete() {
        System.out.println("删除了一个用户");

    }

    public void update() {
        System.out.println("更新了一个用户");

    }

    public void select() {
        System.out.println("查询了一个用户");

    }
}

log:

package com.kuang.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

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

    }
}

package com.kuang.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

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

    }
}

方式2:使用Spring的AOP接口【主要是切面定义】

<?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="userService" class="com.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>

    <bean id="diy" class="com.kuang.diy.DiyPointCut"/>
    <aop:config>
        <aop:aspect ref="diy">
            <aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>

        </aop:aspect>
    </aop:config>


</beans>
package com.kuang.diy;

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

测试:

import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

        userService.add();
    }
}

posted @ 2021-04-02 20:32  豆豆tj  阅读(136)  评论(0)    收藏  举报