@yudesong
2018-02-16T14:28:36.000000Z
字数 3282
阅读 593
AOP
Aspect Oriented Programming 面向方面编程戒面向切面编程
AOP 关注点是共同处理,可以通过配置将其作用到某一个戒多个目标对象上。好处是实现组件重复
利用,改善程序结构,提高灵活性。将共通组件不目标对象解耦。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"xmlns:util="http://www.springframework.org/schema/util"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"><!-- configure the package for spring to scan --><context:component-scan base-package="test.Spring.AOP" /><!-- make the aspectj annotation to be used --><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
public interface HelloWord {public int sayHello(int num);}@Componentpublic class HelloWordImpl implements HelloWord{public int sayHello(int num){System.out.println("hello word");return 100/num;}}
@Component@Aspectpublic class HelloWordAspect {@Before(value="execution(* test.Spring.AOP.HelloWord.sayHello(..))")public void beforeMethod(JoinPoint jp){String methodName = jp.getSignature().getName();System.out.println(methodName);System.out.println("before method execute,args are "+Arrays.toString(jp.getArgs()));}@After("execution(* test.Spring.AOP.HelloWord.sayHello(..))")public void afterMethod(JoinPoint jp){System.out.println("after method execute,args are "+Arrays.toString(jp.getArgs()));}@AfterThrowing(value="execution(* test.Spring.AOP.HelloWord.sayHello(..))",throwing="ex")public void afterThrow(Exception ex){System.out.println("afterThrow"+ex.getMessage());}@AfterReturning(value="execution(* test.Spring.AOP.HelloWord.sayHello(..))",returning="result")public void afterReturn(Object result){System.out.println("the result is "+result);}}
主函数
public class Main {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContextForAOP.xml");HelloWord hw = (HelloWord) context.getBean("helloWordImpl");hw.sayHello(10);}}
@Component@Aspectpublic class HelloWordAspectAround {@Around(value="execution(* test.Spring.AOP.HelloWord.sayHello(..)))")public Object aroundMethod(ProceedingJoinPoint pjp){Object result = null;String methodName = pjp.getSignature().getName();try {result = pjp.proceed();System.out.println("the result is "+result);} catch (Throwable e) {System.out.println("Exception occurs : "+e.getMessage());throw new RuntimeException(e);}System.out.println(methodName+" end");return result;}}