动态代理实现(AspectJ)

来源:互联网 发布:印巴分治原因知乎 编辑:程序博客网 时间:2024/06/18 05:48

 .注解实现
架包
aspectjrt.jar
asm-2.2.3.jar
asm-commons-2.2.3.jar
asm-util-2.2.3.jar
spring.jar
cglib-nodep-2.1_3.jar
log4j-1.2.11.jar
commons-logging-1.0.4.jar
配置AOP.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="
http://www.springframework.org/schema/beans"
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="
http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <aop:aspectj-autoproxy/>
    <bean id="messageSend" class="aopaspectj.MessageSendImp"></bean>
    <bean id="logBeforeAdvice" class="aopaspectj.LogBeforeAdvice"></bean>
</beans>

1.切面类LogBeforeAdvice
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class LogBeforeAdvice {
    @Before("execution(* sendMessage(..))")  //execution()所有sendMessage(..)都拦截
    public void before(JoinPoint point) {
        System.out.println("+++++ before call sendMessage +++++++++");
        System.out.println("Logging before  "+point.getSignature().getName());
    }
    @Around("execution(* sendMessage(..))")
    public void LogforLogin(ProceedingJoinPoint point) throws Throwable{
        String i = (String)point.proceed();
        System.out.println(" around getMessage is" + i);
    }
}
2.接口MessageSend
public interface MessageSend {
    String sendMessage(String message);
    void sendMessage(String s1,String s2);
}
3.实现类MessageSendImp
public class MessageSendImp implements MessageSend {

    public String sendMessage(String message) {
        System.out.println(" =============== Send mesage :" + message+" ===========");
        return message;
    }
    public void sendMessage(String s1, String s2) {
        System.out.println("=============="+s1+"==========="+s2);
    }
}
4.Main
public class Main {
    public static void main(String[] args) {
        ClassPathResource s = new ClassPathResource("/AOP.xml");
        BeanFactory f = new XmlBeanFactory(s);
        MessageSend sender = (MessageSend) f.getBean("messageSend");
        AspectJProxyFactory factory = new AspectJProxyFactory();
        factory.setTarget(sender);
        factory.addAspect(LogBeforeAdvice.class);
        MessageSendImp m = factory.getProxy();
        m.sendMessage("Bill");
        System.out.println("======================================");
        m.sendMessage("Nihao", "Bill");
    }
}

原创粉丝点击