本文主要是介绍spring aop横切对象、切面参数传递,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.
spring.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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="testaspect" class="com.spring.TestAspect"></bean>
<bean id="testbiz" class="com.spring.TestBiz"></bean>
<aop:config>
<aop:pointcut expression="execution(* com.spring.TestBiz.biz(String,String)) and args(name,password)" id="testpoint"/>
<aop:aspect ref="testaspect">
<aop:before method="save" pointcut-ref="testpoint" arg-names="name,password"/>
<!--
<aop:after method="del" pointcut-ref="testpoint"/>
<aop:around method="total" pointcut-ref="testpoint"/>
-->
</aop:aspect>
</aop:config>
</beans>
2.业务类(横切对象)
package com.spring;
public class TestBiz {
private String name;
private String password;
public void biz(String name,String password){
this.name=name;
this.password=password;
}
public String aa(){
//System.out.println(this.name);
return this.name;
}
}
3.切面
package com.spring;
import org.aspectj.lang.ProceedingJoinPoint;
public class TestAspect {
private String name;
private String password;
public void save(String name,String password){
System.out.println("guo="+name);
System.out.println("password="+password);
this.name=name;
this.password=password;
System.out.println(this.name);
}
public String aa(){
// System.out.println(this.name);
return this.name;
}
public String del(){
String name2="name2";
System.out.println("aspect del....");
return name2;
}
//环绕通知需要携带ProceedingJoinPoint类型的参数
public void total(ProceedingJoinPoint p){
String className=p.getTarget().getClass().getName();
String method=p.getSignature().getName();
try {
long start=System.currentTimeMillis();
System.out.println("start="+start);
p.proceed();
long end=System.currentTimeMillis();
System.out.println("end="+end);
System.out.println(className+"类的"+method+"方法"+"执行了"+(end-start)+"长时间");
} catch (Throwable e) {
e.printStackTrace();
}
}
}
4.测试类
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
TestBiz biz=(TestBiz)context.getBean("testbiz");
biz.biz("guooo","123456");
}
}
打印结果:
这篇关于spring aop横切对象、切面参数传递的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!