SpringBoot学习之自定义注解与aop切面的使用,通过使用自定义注解和aop切面来调用service层方法和参数等。
一 . 自定义注解类,我们先自定义一个@Action注解,代码如下。
package com.casking.chcs.modules.test.service; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义注解(元数据) * @author Anson * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { String name(); String hello(); }
二 . 在我们自定义的DemoAnnotationService类中(即service层中)使用我们自定义的@Action注解。
package com.casking.chcs.modules.test.service; import org.springframework.stereotype.Service; @Service public class DemoAnnotationService { @Action(name = "注解式拦截的add操作", hello = "hello,我在这") public void add() { System.out.println("调用了add方法"); }; }
三 . aop扫描配置类,指定我们的扫描范围为service层下的类,代码如下。
package com.casking.chcs.modules.test.service; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * * 配置类 * @author Anson * */ @Configuration //注册被spring管理 @ComponentScan("com.casking.chcs.modules.test.service") //指定扫描范围 @EnableAspectJAutoProxy //注解开启对aspectJ的支持 public class AopConfig { }
四 .aop切面类,通过反射获取我们扫描的信息,如@Action注解上的信息。
package com.casking.chcs.modules.test.service; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; /** * 编写切面 * * @author Anson * */ @Aspect // 注解声明一个切面 @Component // 受spring管理的容器 public class LogAspect { @Pointcut("@annotation(com.casking.chcs.modules.test.service.Action)") // 注解声明切点 public void annotationPointcut() { }; @After("annotationPointcut()") public void after(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature(); Method method = methodSignature.getMethod(); Action annotation = method.getAnnotation(Action.class); System.out.println("注解式拦截 : " + annotation.name()); System.out.println("????: " + annotation.hello()); } }
一 .容器启动类
package com.casking.chcs.modules.test.web; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.casking.chcs.modules.test.service.AopConfig; import com.casking.chcs.modules.test.service.DemoAnnotationService; public class Main { public static void main(String[] args) { //初始化容器 AnnotationConfigApplicationContext countext = new AnnotationConfigApplicationContext(AopConfig.class); //获得Bean DemoAnnotationService bean = countext.getBean(DemoAnnotationService.class); //调用方法 bean.add(); countext.close(); } }
六 . 输出结果