aop操作-环绕通知获取数据的案例

添加ResourcesService,ResourcesServiceImpl,ResourcesDao和ResourcesDaoImpl类

public interface ResourcesDao {
    boolean readResources(String url, String password);
}
@Repository
public class ResourcesDaoImpl implements ResourcesDao {
    public boolean readResources(String url, String password) {
        //模拟校验
        return password.equals("root");
    }
}
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);
    }
}

创建Spring的配置类

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

编写通知类并添加环绕通知

@Component
@Aspect
public class MyAdvice {
    @Pointcut("execution(* com.itheima.service.ResourcesService.openURL(String, String))")
    private void servicePt(){}

    @Around("servicePt()")
    public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        System.out.println("去除空格前参数信息:" + Arrays.toString(args));
        // 去除参数两端的多余空格
        for(int i = 0; i < args.length; i++){
            // 判断是否为字符串类型
            if(args[i].getClass().equals(String.class)){
                args[i] = args[i].toString().trim();
            }
        }
        System.out.println("去除空格后参数信息:" + Arrays.toString(args));

        // 一定要方改为后的数组args,如果不把args传入的话,运行原始方法使用的还是原来的参数
        Object ret = pjp.proceed(args);
        return ret;
    }
}

运行程序

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

 


 

posted @ 2023-06-04 16:37  Mr_sven  阅读(37)  评论(0编辑  收藏  举报