1、新建一个工程,导入相应的jar包
aopalliance.jar
aspectjweaver.jar
commons-logging-1.2.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
2、建立需要切面编程的类
package com.sun.spring.stu.aop; public interface ArithmaticCaculator { int add(int i, int j); int sub(int i, int j); int mul(int i, int j); int div(int i, int j); } package com.sun.spring.stu.aop; import org.springframework.stereotype.Component; @Component("arithmaticCaculator") public class ArithmaticCaculatorImpl implements ArithmaticCaculator { @Override public int add(int i, int j) { return i+j; } @Override public int sub(int i, int j) { return i-j; } @Override public int mul(int i, int j) { return i*j; } @Override public int div(int i, int j) { return i/j; } }
3、建立切面类
package com.sun.spring.stu.aop; import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(public int com.sun.spring.stu.aop.ArithmaticCaculator.*(int,int))") public void beforeMethod(JoinPoint joinPoint){ String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("The method "+ methodName+" begain with:" +Arrays.asList(args)); } }
4、配置IOC容器
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.sun.spring.stu.aop"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
5、调用需要切面编程的类,自然就会调用切面类中的相关代码
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ArithmaticCaculator caculator = (ArithmaticCaculator) ctx.getBean("arithmaticCaculator"); int result = caculator.add(21, 90); System.out.print("The result:"+result);
6、结果:
2016-2-6 12:01:53 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org[email protected]2be9cb75: startup date [Sat Feb 06 12:01:53 CST 2016]; root of context hierarchy
2016-2-6 12:01:53 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
The method add begain with:[21, 90]
The result:111