需求:对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理
分析:
1、在业务方法执行之前对所有的输入参数进行格式出——trim()
2、使用处理后的参数调用原始方法——环绕通知中存在对原始方法的调用
代码实现:
ResourcesService业务层接口:
public interface ResourcesService { public boolean openURL(String url ,String password); }
ResourcesServiceImpl业务层实现类:
import com.itheima.dao.ResourcesDao; import com.itheima.service.ResourcesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ResourcesServiceImpl implements ResourcesService { @Autowired private ResourcesDao resourcesDao; public boolean openURL(String url, String password) { return resourcesDao.readResources(url,password); } }
ResourcesDao数据层接口:
public interface ResourcesDao { boolean readResources(String url, String password); }
ResourcesDaoImpl数据层实现类:模拟校验
import com.itheima.dao.ResourcesDao; import org.springframework.stereotype.Repository; @Repository public class ResourcesDaoImpl implements ResourcesDao { public boolean readResources(String url, String password) { //模拟校验 return password.equals("root"); } }
SpringConfig配置类:
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @ComponentScan("com.itheima") @EnableAspectJAutoProxy public class SpringConfig { }
DataAdvice的aop类:
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component @Aspect public class DataAdvice { @Pointcut("execution(boolean com.itheima.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)){ //取出数据,trim()操作后,更新数据 args[i] = args[i].toString().trim(); } } Object ret = pjp.proceed(args); return ret; } }
App运行类:
import com.itheima.config.SpringConfig; import com.itheima.service.ResourcesService; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; 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/haha", "root "); } }
执行结果:
可以看出,不管加不加空格,对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理的需求已经解决。如果有些相同的大量使用的功能,需要在很多地方加的话,使用AOP是你的不二选择。使用AOP能简化你的共性功能的开发。