spring Ioc注解配置
不使用xml,纯java配置Ioc,首先创建一个mave工程,导入jar依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
</dependencies>
我们首先创建一个配置类Config.java
@EnableAspectJAutoProxy //开启自动代理
@Configuration
@ComponentScan(basePackages = "org.youyuan")
public class Config {
}
@EnableAspectJAutoProxy表示开启自动代理,相当于application.xml当中的
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Configuration表示当前是一个配置类
@ComponentScan(basePackages = “org.youyuan”)表示扫码当前包位置下的所有的类
在创建一个类,拦截其中的方法
Calculate.java
@Component
public class Calculate {
public int add(int a,int b){
return a+b;
}
}
定义一个切面类
aspect.java
@Component
@Aspect
public class aspect {
/*统一定义切点*/
@Pointcut("execution(* org.youyuan.aop.Calculate.add(..))")
public void pointcut(){
}
/*前置通知*/
@Before(value ="pointcut()")
public void before(JoinPoint point){
System.out.println("before");
String name = point.getSignature().getName();
System.out.println(name);
}
/*后置通知*/
@After(value = "pointcut()")
public void after(JoinPoint joinPoint){
System.out.println("after");
String name = joinPoint.getSignature().getName();
System.out.println(name);
}
/*返回通知*/
@AfterReturning(value = "pointcut()" ,returning = "res")
public void afterReturning(JoinPoint point,int res){
System.out.println("afterReturning----->结果为="+res);
String name = point.getSignature().getName();
System.out.println(name);
}
/*异常通知*/
@AfterThrowing(value = "pointcut()",throwing = "e")
public void afterThrowing (JoinPoint point,Exception e) {
System.out.println("afterThrowing");
System.out.println("异常为-->"+e);
String name = point.getSignature().getName();
System.out.println(name);
}
/*环绕通知*/
@Around(value = "pointcut()")
public int around (ProceedingJoinPoint joinPoint){
System.out.println("around1");
try {
Object proceed = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("around2");
return 4;
}
}
@Aspect表示当前类是一个切面类
运行程序
@Test
public void test6(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Calculate bean = context.getBean(Calculate.class);
bean.add(1,2);
}
结果
从结果当中我们可以看出,环绕通知的 Object proceed = joinPoint.proceed();方法的前面相当于是前置通知,后面相当于是后置通知,且因为环绕通知的执行return的时候比add方法执行return的时间晚,所有把原结果3给覆盖掉了,所以返回通知的结果是4。