标签:配置 system time inter pack ble frame 示例 highlight
1、利用注解实现AOP的基本流程
1.2、创建一个service,使用上面定义的注解来指定切点
1.3、创建Aspect,增加业务逻辑
1.4、创建Spring配置类
1.5、测试
2、获取自定义注解的参数
Spring中,可以通过自定义注解的方式来实现AOP,比如下面简单的示例:
package cn.ganlixin.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DemoAnnotation {
//注意这里没有定义属性
}
这里为了节约篇幅,就不创建service接口,再创建serviceImpl来实现接口了,直接写在service中:
package cn.ganlixin.service;
import cn.ganlixin.annotation.DemoAnnotation;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@DemoAnnotation // 使用自定义的注解,声明该方法为切点方法
public void demo() {
System.out.println("this is DemoService.demo()");
}
}
package cn.ganlixin.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class DemoAspect {
@Before("@annotation(cn.ganlixin.annotation.DemoAnnotation)")
public void demoBefore() {
System.out.println("this is before output message");
}
}
主要做的是:指定包扫描路径
package cn.ganlixin;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("cn.ganlixin")
@EnableAspectJAutoProxy
public class AppConfig {
}
package cn.ganlixin;
import cn.ganlixin.service.DemoService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
@Test
public void testAOP1() {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
DemoService demoService = context.getBean(DemoService.class);
demoService.demo();
}
}
输出:
this is before output message this is DemoService.demo()
标签:配置 system time inter pack ble frame 示例 highlight
原文地址:https://www.cnblogs.com/-beyond/p/11387487.html