飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

实体类:

package com.student.jdk;
//作为实体类
public class UserDaoImpl implements UserDao {

	@Override
	public void addUser() {
		System.out.println("添加用户!!");
	}

	@Override
	public void deleteUser() {
		System.out.println("删除用户!!");

	}

}

切面类:

package com.student.factorybean;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyAspect implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation arg0) throws Throwable {
		check_Permissions();//调用自己的模拟检查权限方法。
		Object obj = arg0.proceed();//执行目标方法。
		log();//调用自己的模拟记录日志方法。
		
		return null;
	}

	private void log() {
	System.out.println("模拟检查记录日志!!!!");
		
	}

	private void check_Permissions() {
		System.out.println("模拟检查权限!!!");
		
	}

}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- services -->

	<bean id="userDao" class="com.student.jdk.UserDaoImpl"></bean>
	<bean id="myAspect" class="com.student.factorybean.MyAspect"></bean>
	<bean id="userDaoProxy"
		class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="proxyInterfaces"
			value="com.student.jdk.UserDao"></property>
	    <property name="target" ref="userDao"></property>
		<property name="interceptorNames" value="myAspect"></property>
		<property name="proxyTargetClass" value="true"></property>
	</bean>

</beans>

测试类:

package com.student.factorybean;

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

import com.student.jdk.UserDao;

public class ProxyFactorBeanTest {

	public static void main(String[] args) {
		String xmlPath = "com/student/factorybean/applicationContext.xml";
		ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
		UserDao userDao =(UserDao)applicationContext.getBean("userDaoProxy");
		userDao.addUser();
		userDao.deleteUser();
	}

}

运行结果:

十月 16, 2019 5:23:13 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@25f38edc: startup date [Wed Oct 16 17:23:13 CST 2019]; root of context hierarchy
十月 16, 2019 5:23:13 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/factorybean/applicationContext.xml]
模拟检查权限!!!
添加用户!!
模拟检查记录日志!!!!
模拟检查权限!!!
删除用户!!
模拟检查记录日志!!!!

posted on 2019-10-16 17:26  飞行的猪哼哼  阅读(32)  评论(0)    收藏  举报