<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!--使用AspectJ方式注解需要相应的包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!--使用AspectJ方式注解需要相应的包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
package gaofeng.aspectj;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@EnableAspectJAutoProxy
@ComponentScan({"gaofeng.aspectj"})
public class TestAop {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestAop.class);
// FF c = context.getBean(FF.class);
Controller c = context.getBean(Controller.class);
c.say("word");
context.close();
}
}
//当切面在接口函数上时,必须用接口类。如 FF c = context.getBean(FF.class);也可以通过设置这个参数,可以避免。@EnableAspectJAutoProxy(proxyTargetClass=true)
//interface FF{
// public void say(String word);
//}
//@Service
//class Controller implements FF{
// public void say(String word) {
// System.out.println("hello " + word);
// }
//}
@Service
class Controller{
public String say(String word) {
System.out.println("hello " + word);
return "hello " + word;
}
}
@Component
@Aspect
class MyAspect {
@Pointcut("execution(* gaofeng.aspectj.Controller.*(..))")
public void pointcut(){
}
@Before("pointcut()")
public void before(JoinPoint joinPoint){
System.out.println("前置通知!" + joinPoint.getSignature());
System.out.println("前置通知!" + joinPoint.getArgs()[0]);
System.out.println("前置通知!" + joinPoint.toString());
}
@After("pointcut()")
public void after(){
System.out.println("后置通知!");
}
@AfterReturning(pointcut="pointcut()",returning="retVal")
public void afterReturn(String retVal) {
System.out.println("@AfterReturning 返回值是" + retVal );
}
@Around("pointcut()")
public Object modifyParm(ProceedingJoinPoint joinPoint) {
System.out.println("111111 @Around");
Object obj = null;
try {
obj = joinPoint.proceed(new String[] {"bbb"});
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("22222222 修改函数的入参 @Around");
return obj;
}
}
spring aop
最新推荐文章于 2021-05-09 11:26:12 发布