Spring AOP实战:百度网盘密码数据兼容处理

案例:百度网盘密码数据兼容处理

1. 需求和分析

需求:对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理

例如下面的百度网盘分享链接

链接:https://pan.baidu.com/s/1xUQ1Zg3GqKLZXrME9y81cw?pwd=1fi8 
提取码:1fi8 
--来自百度网盘超级会员V6的分享

我们复制密码的时候有时候可能会把后面默认添加的空格复制上,但是即使我们加了空格,百度网盘依然能识别密码,这是怎么做的呢?
在这里插入图片描述

有同学肯定会说,害,直接在函数里对字符串处理呗,但是随着业务的增多,不止获取网盘资源要去除这个空格,当还有其他业务要进行这样的操作的时候,我们还得再写一遍代码非常的麻烦,所以,用AOP就能很好的完成这个需求

想到了AOP,我们再来理一下这里面实现的逻辑

通知中实现的步骤:

  1. 在业务方法执行之前对所有的输入参数进行格式处理——trim()
  2. 使用处理后的参数调用原始方法——环绕通知中存在对原始方法的调用

那么用什么通知才能完成这个需求呢?

涉及数据操作,一般用环绕

2. 代码实现

模拟环境准备

//-------------service层代码-----------------------
public interface ResourcesService {
    
    
    public boolean openURL(String url ,String password);
}
@Service
public class ResourcesServiceImpl implements ResourcesService {
    
    
    @Autowired
    private ResourcesDao resourcesDao;

    public boolean openURL(String url, String password) {
    
    
        return resourcesDao.readResources(url,password);
    }
}


//-------------dao层代码-----------------------
public interface ResourcesDao {
    
    
    boolean readResources(String url, String password);
}
@Repository
public class ResourcesDaoImpl implements ResourcesDao {
    
    
    public boolean readResources(String url, String password) {
    
    
        System.out.println(password.length());
        //模拟校验
        return password.equals("root");
    }
}

编写通知类

@Component
@Aspect
public class DataAdvice {
    
    
    
    @Pointcut("execution(boolean com.yyl.service.*Service.*(*,*))")
    private void servicePt(){
    
    }

    @Around("DataAdvice.servicePt()")
    public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {
    
    
        Object[] args = pjp.getArgs();
        for (int i = 0; i < args.length; i++) {
    
    
            //判断参数是不是字符串
            if(args[i].getClass().equals(String.class)){
    
    
                args[i] = args[i].toString().trim();
            }
        }
        Object ret = pjp.proceed(args);
        return ret;
    }
}

在SpringConfig配置类上开启AOP注解功能

@Configuration
@ComponentScan("com.yyl")
@EnableAspectJAutoProxy
public class SpringConfig {
    
    
}

运行测试类,查看结果

public class App {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        ResourcesService resourcesService = ctx.getBean(ResourcesService.class);
        boolean flag = resourcesService.openURL("http://pan.baidu.com/dongqilai", "root ");
        System.out.println(flag);
    }
}

运行结果如下:
在这里插入图片描述
说明处理成功了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45525272/article/details/125956506