Spring—Aop切面编程

一、接口类

public interface UserService {
	
	public void addUser();
	public void updateUser();
	public void deleteUser();

}

二、实现类

public class UserServiceImpl implements UserService{
	@Override
	public void addUser() {
		System.out.println("spring_aop.factorybean:addUser");
	}
	@Override
	public void updateUser() {
		System.out.println("spring_aop.factorybean:updateUser");
	}
	@Override
	public void deleteUser() {
		System.out.println("spring_aop.factorybean:deleteUser");
	}
}

三、切面类

public class MyAspect implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		
		System.out.println("前4");
		Object object = mi.proceed();
		System.out.println("后4");
		return object;
	}
}

四、测试类

public class TestSpringAop {
	
	@Test
	public void deom1(){
		
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		UserService service = (UserService) context.getBean("userServiceId");
		service.addUser();
		service.updateUser();
		service.deleteUser();
	}

}

五、applicationContext.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	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.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop  
    	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    	http://www.springframework.org/schema/task  
		http://www.springframework.org/schema/task/spring-task-3.1.xsd"
	default-lazy-init="true">

	<!-- 1 创建目标类 -->
	<bean id="userServiceId" class="com.bsoft.cn.spring_aop.UserServiceImpl"/>
	<!-- 2 创建切面类(通知) -->
	<bean id="myAspectId" class="com.bsoft.cn.spring_aop.MyAspect"/>
	<!-- 3 aop编程 
		3.1 导入命名空间
		3.2 使用 <aop:config>进行配置
				proxy-target-class="true" 声明时使用cglib代理
			<aop:pointcut> 切入点 ,从目标对象获得具体方法
			<aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
				advice-ref 通知引用
				pointcut-ref 切入点引用
		3.3 切入点表达式
			execution(* com.itheima.c_spring_aop.*.*(..))
			选择方法         返回值任意   包             类名任意   方法名任意   参数任意
		
	-->
	<aop:config>
	  <aop:pointcut expression="execution(* com.bsoft.cn.spring_aop.*.*(..))" id="myPointCut"/>
	  <aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
	</aop:config>
</beans>



猜你喜欢

转载自blog.csdn.net/dc282614966/article/details/80851890
今日推荐