Aop代理around例子和需要jar包

需要的jar包:
aspectjrt.jar
aopalliance.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar

Aop例子:
context_aop.xml配置文件:
<bean id="fooService" class="spring.aop.DefaultFooService" />
<bean id="aopInject" class="spring.aop.AopInject"></bean>
<aop:config>
  <aop:aspect ref="aopInject">
    <aop:pointcut expression="execution(* spring.aop.FooService.getFoo(String,int))" id="allExecution"/>
    <aop:around method="injectMethod" pointcut-ref="allExecution"/>
  </aop:aspect>
</aop:config>


AopInject类, 代理类:
public class AopInject {
  public Object injectMethod(ProceedingJoinPoint call) throws Throwable {
    System.out.println("AopInject类注入");
    return call.proceed();
  }
}


接口类:
public class Foo {
  public Foo(String name, int age){
    System.out.println("foo类初始化");
  }
}
public interface FooService {
  Foo getFoo(String fooName, int age);
}
public class DefaultFooService implements FooService {
  public Foo getFoo(String name, int age) {
    return new Foo(name, age);
  }
}


执行类:
BeanFactory ctx = new ClassPathXmlApplicationContext("context_aop.xml");
FooService foo = (FooService) ctx.getBean("fooService");
foo.getFoo("Pengo", 12);


注意事项PS:
一: 如果代理类需要用到代理的值, 例如foo.getFoo("Pengo", 12), 则可以在配置文件中加入expression="execution(* spring.aop.FooService.getFoo(String,int)) and args(name,age)"
代理类的代理方法改为:
public Object injectMethod(ProceedingJoinPoint call,String name,int age)
二: AopInject为代理类,必须有返回值,如果是成功,则返回call.proceed(),这样就可以直接到本体类,否则则不进入本体类

你可能感兴趣的:(round)