您的位置:首页 > 编程语言 > ASP

Spring:aspectj

2015-06-29 22:41 676 查看
导入jar包:

com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.1.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

<?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"
xmlns:context="http://www.springframework.org/schema/context"
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.text.aop"></context:component-scan>
<!-- 加入使 AspjectJ 注解起作用的配置 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>


package com.text.aop;

public interface Arithmetic {

public abstract int add(int j,int i);

public abstract int div(int j,int i);
}

package com.text.aop;

import org.springframework.stereotype.Component;

@Component("arithmetic")
public class ArithmeticImpl implements Arithmetic{

@Override
public int add(int j, int i) {
return i+j;
}

@Override
public int div(int j, int i) {
return i/j;
}

}


View Code
* 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解
* 声明是一个切面: 添加 @Aspect
* 声明通知: 即额外加入功能对应的方法.
* 前置通知: @Before("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(int, int))")
* @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体.
* @Before 里面的是切入点表达式:

* 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数.

package com.text.aop;

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

@Aspect//通过添加 @Aspect 注解声明一个 bean 是一个切面!
@Component
public class LoggingAspectj {
@Before("execution(public int com.text.aop.Arithmetic.*(int, int))")
public void adding(JoinPoint join){
String name=join.getSignature().getName();
System.out.println("befor  add : "+name);
}
}


package com.text.aop;

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

public class TestMain {
public static void main(String[] args) {
//创建Spring的IOC容器
ApplicationContext acon=new ClassPathXmlApplicationContext("application.xml");
//从容器中获取bean的实例
Arithmetic ai=(Arithmetic) acon.getBean("arithmetic");
//使用bean
int result=ai.add(12, 4);
System.out.println("result:"+result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: