欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring aop实例

程序员文章站 2022-03-03 09:42:11
...

 

package com.mangocity.spring.test;

/**
 * 切面类
 * @author test
 *
 */
public class Spring3_1Test {

	public void beforePrintContent(String name)  {
		System.out.println("beforePrintContent..."+name);
	} 
	
	public void afterPrintContent()  {
		System.out.println("afterPrintContent...");
	} 
}

package com.mangocity.spring.test;

/**
 * 目标类
 * @author test
 *
 */
public class Spring {
	public void argsTest(String name) {
		System.out.println(name);
	}
}

spring配置
<?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="salService" class="com.mangocity.spring.test.Spring"/>
   <bean id="implement" class="com.mangocity.spring.test.Spring3_1Test"/>
   
   <aop:config>
      <!-- 切入点 有参数 -->
      <aop:pointcut id="pointcut" expression="execution(* com.mangocity..*.*.*(..)) and args(arg1)"/>
      <aop:aspect ref="implement">  
          <!-- 有参数传值  arg-names的名字需与args中的参数名一致 -->      
          <aop:before pointcut-ref="pointcut" method="beforePrintContent" arg-names="arg1"/>
          <!-- 无参数 -->
          <aop:after pointcut="execution(* com.mangocity..*.*.*(..))" method="afterPrintContent"/>
      </aop:aspect>
   </aop:config>   
</beans>

测试类:
package com.mangocity.spring.test;

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

public class SpringTest {
	public static void main(String[] args) {
           ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
           Spring s = (Spring) context.getBean("salService");
           s.argsTest("测试");
	}
}

输出结果:
beforePrintContent...测试
测试
afterPrintContent...