SpringAop应用二之Aop实现Redis缓存(自定义注解实现切入)

22 篇文章 0 订阅
5 篇文章 0 订阅

代码源地址:https://github.com/haijiao12138/Spring.git

一.首先实现自定义注解@AutowireRedis,实现该注解的方法会自动实现切面

首先引入redis依赖:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
package com.haijiao12138.demo.spring.util;
import java.lang.annotation.*;

/**
 * @author haijiao12138
 * @date 2021/8/12 20:57
 * @description
 */

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AutowireRedis {
}

二.自定义包中实现自定义注解@AutowireRedis

package com.haijiao12138.demo.spring.aop0812.controller;


import com.haijiao12138.demo.spring.util.AutowireRedis;
import com.haijiao12138.demo.spring.util.DataChange;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: haijiao12138
 * @ClassName: AopController
 * @description: TODO
 * @date: 2021/8/12 19:35
 *
 */
@RestController
@RequestMapping("/aop")
public class AopController {

    List<Object> list = new ArrayList<>();
    @RequestMapping("/data")
    @AutowireRedis
    public List<Object> test(){

        list.add("张三");
        list.add("李四");
        return list;
    }

    @RequestMapping("/addData")
    @DataChange(name = "AopController")
    public List<Object> addData(){

        list.add("王五");
        list.add("赵六");
        return list;
    }

}

三.切面类中对切面升级;

package com.haijiao12138.demo.spring.aop0812;

import com.haijiao12138.demo.spring.util.AutowireRedis;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author: haijiao12138
 * @ClassName: WebAspect
 * @description: TODO
 * @date: 2021/8/12 19:32
 */
@Aspect
@Component
public class WebAspect {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 切入点,基于注解实现的切入点  加上该注解的都是Aop切面的切入点
     * 匹配top.alanlee.template.controller包及其子包下的所有类的所有方法
     */
    @Pointcut("@annotation(com.haijiao12138.demo.spring.util.AutowireRedis)")
    public void pointCut() {
    }


    /**
     * 环绕通知
     * 环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值。
     * 环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型
     *
     * @param proceedingJoinPoint
     */
    @Around("pointCut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
        System.out.println("----------- 环绕通知 -----------");
        Signature signature = proceedingJoinPoint.getSignature();

        System.out.println("环绕通知的目标方法名:" + proceedingJoinPoint.getSignature().getName());

        String key1 = new StringBuilder().append(signature).toString();
        String key = key1.replace(" ", ".");
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s == null) {//如果在redis中没取到值 将方法的路径作为key  将切面运行结果作为value存入redis中 供下一次查询使用
            try {
                Object proceed = proceedingJoinPoint.proceed();
                stringRedisTemplate.opsForValue().set(key, String.valueOf(proceed));
                return proceed;
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
        //如果第一次在redis中能取到值  s就不为空  直接将s返回
        return Arrays.asList(s.replace("[", "").replace("]", "").split(","));

    }

}

四:结果展示

页面结果:

 redis结果:

redis中查看结果 需要安装redis可视化工具进行查看即可;

项目路径如下:

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Spring AOP来通过自定义注解实现切入点。首先,定义一个自定义注解,并在需要切入的方法上使用该注解,然后定义一个切面,并在切面中使用@Before 或 @Around 注解来拦截被标记的方法,最后,在Spring的配置文件中声明所需的切面,此时,所有被标记的方法都会被拦截。 ### 回答2: 使用Spring AOP切入定义注解有以下几个步骤: 1. 在项目中引入Spring AOP的依赖,一般为spring-aop和spring-aspects。 2. 在配置文件中开启Spring AOP的自动代理功能。可以通过在XML配置文件中添加<aop:aspectj-autoproxy />或在Java配置文件中添加@EnableAspectJAutoProxy注解实现。 3. 创建一个切面类,用于定义切入的逻辑。这个类需要使用@Component或者其他Spring注解进行标识,以便Spring能够扫描到。 4. 在切面类的方法中,使用@Before、@After等注解定义切入点和具体的切入操作。例如,使用@Before注解定义在某个注解标记的方法执行之前切入的逻辑。 5. 在注解定义定义的切点。可以使用@Retention和@Target等元注解来配置注解的生命周期和使用范围。 6. 在目标类或方法上添加自定义注解。例如,在一个Service类的某个方法上添加自定义注解。 7. 运行项目,Spring会根据配置自动代理目标类,当目标类或方法被调用时,切面类中定义切入逻辑就会自动被执行。 8. 可以通过配置切入的顺序、通知的类型等来进一步细化切入的逻辑。 通过以上步骤,我们可以使用Spring AOP方便地切入定义注解实现对目标类或方法的增强、日志记录、权限控制等功能。 ### 回答3: 使用Spring AOP切入定义注解需要以下几个步骤: 1. 定义一个自定义注解。可以使用Java提供的`@interface`关键字创建一个注解,例如: ```java @Target(ElementType.METHOD) // 定义注解的作用范围为方法 @Retention(RetentionPolicy.RUNTIME) // 注解在运行时可见 public @interface CustomAnnotation { // 自定义注解的属性 } ``` 2. 创建一个切面类来处理注解。可以使用Spring提供的`@Aspect`注解来标记切面类,并在方法上使用`@Before`、`@After`等注解定义切入点和增强逻辑。例如: ```java @Aspect @Component public class CustomAspect { @Before("@annotation(customAnnotation)") // 拦截带有CustomAnnotation注解的方法 public void beforeMethod(CustomAnnotation customAnnotation) { // 在方法执行前执行的逻辑 } } ``` 3. 配置Spring AOP。在Spring配置文件中添加AOP的配置,例如使用`<aop:aspectj-autoproxy>`标签开启自动代理,并指定切面类的包名,让Spring能够自动扫描并应用切面逻辑。 4. 在目标方法上使用自定义注解。在需要切入的方法上标记使用自定义注解,例如: ```java @CustomAnnotation public void doSomething() { // 方法的实际逻辑 } ``` 这样,在调用`doSomething()`方法时,Spring AOP会拦截到带有`@CustomAnnotation`注解的方法,并执行切面逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值