您的位置:首页 > 编程语言 > Java开发

Spring学习(九)-AOP切面通知

2017-08-18 11:19 369 查看
重点笔记(前置与后置通知):

1.导入所需的jar包

2.在配置文件中加入aop命名空间

3.基于注解的方式:

1)使Aspjectj注解起作用:自动为匹配的类生成代理对象

`<aop:aspectj-autoproxy></aop:aspectj-autoproxy>


2)把横切关注点的代码抽象到切面的类中,切面首先是个IOC中的bean,即加入@Component注解

切面还需要加入@Aspect注解

3)在类中声明一个方法,方法前加上@Before @After注解:

@Before(“execution(public int com.spring.aop.impl.AtithmeticCalculatior.*(int , int ))”)

可以在通知方法中声明一个类型为JoinPoint的参数 就能访问链接细节,如方法名称和参数值

1.applicationCont.xml文件

<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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 
<context:component-scan
base-package="com.spring.aop.impl">
</context:component-scan>

<!-- 使Aspjectj注解起作用:自动为匹配的类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>


2.LoggingAspect.java切面类

package com.spring.aop.impl;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//把这个类声明为一个切面:需要把该类放在IOC容器中、再声明一个切面
@Aspect
@Component
public class LoggingAspect {

//声明该方法是一个前置通知,在目标方法开始之前执行
@Before("execution(public int com.spring.aop.impl.AtithmeticCalculatior.*(int , int ))")
public void beforeMethod(JoinPoint joinPoint) {

String methodname=joinPoint.getSignature().getName();
List<Object> args=Arrays.asList(joinPoint.getArgs());
System.out.println("The method begins "+methodname+" begins with "+args);
}

}


3.Main.java测试类

package com.spring.aop.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext ctx=new ClassPathXmlApplicationContext("springXML/applicationContext.xml");
AtithmeticCalculatior atithmeticCalculatior=ctx.getBean(AtithmeticCalculatior.class);
int result=atithmeticCalculatior.add(3, 4);
System.out.println(result);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring bean