
java advice是什么,让我们一起了解一下?
Advice是在Join Point上执行的一个动作或者通知,一般通过拦截器调用。Spring有两大核心,IOC和AOP,在模块AOP里面有个advice。
在Spring-AOP中,增强(Advice)是如何实现的?
按照增强在目标类方法连接点的位置可以将增强划分为以下五类:
前置增强 (org.springframework.aop.BeforeAdvice) 表示在目标方法执行前来实施增强。
后置增强 (org.springframework.aop.AfterReturningAdvice)表示在目标方法执行后来实施增强。
环绕增强 (org.aopalliance.intercept.MethodInterceptor)表示在目标方法执行前后同时实施增强。
异常抛出增强 (org.springframework.aop.ThrowsAdvice) 表示在目标方法抛出异常后来实施增强。
引介增强 (org.springframework.aop.introductioninterceptor)表示在目标类中添加一些新的方法和属性。

实战操作:Spring中Advice简单案例
1、配置类
@Configuration//配之类
@EnableAspectJAutoProxy//启用AspectJ自动代理
@ComponentScan(basePackages = {"spring01","spring02"}) //basePackages指定扫描的包
public class Config {
}2、切面类
@Aspect
@Component
public class Audience {
/**
* 相当于访问相同报下的不同的类,他们拥有相同的包路径,可以定义一个变量
*/
@Pointcut("execution(* spring02.aspect.Performance.perform(..))")
public void performance(){
}
@Before("performance()")
public void silenceCellPhones(){
System.out.println("====表演前将手机调静音");
}
@Before("performance()")
public void takeSeats(){
System.out.println("====表演前就做");
}
@AfterReturning("performance()")
public void applause(){
System.out.println("====表演后鼓掌");
}
@AfterThrowing("performance()")
public void demandRefund(){
System.out.println("====表演失败时退款");
}
@Around("performance()")
public void watchPerformance(ProceedingJoinPoint point){
try {
System.out.println("====观看前1");
point.proceed();
System.out.println("====观看后2");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}3、被通知对象接口
public interface Performance {
void perform();
}4、被通知对象实现类
@Component("performance")
public class PerformanceImpl implements Performance{
@Override
public void perform() {
System.out.println("======表演开始=====");
}
}5、测试类
@RunWith(SpringJUnit4ClassRunner.class)//启动测试时创建Spring上下文
@ContextConfiguration(classes = {Config.class})//配置文件对象
public class TestClass {
@Autowired
private Performance performance;
@Test
public void test(){
performance.perform();
}
}以上就是小编今天的分享了,希望可以帮助到大家。
