Spring框架之面向切面编程AOP(1.0)
AOP初步实现:
定义一个业务层:
1,定义IMessageService接口
package cn.mldn.service;
public interface IMemberService {
public boolean delete(String mid) throws Exception;
}
2,实现该接口MessageService
package cn.mldn.service.impl;
import org.springframework.stereotype.Service;
import cn.mldn.service.IMemberService;
@Service
public class MemberServiceImpl implements IMemberService {
@Override
public boolean delete(String mid) throws Exception {
System.out.println("********* 【MemberService】数据删除处理。");
return false;
}
}
3,定义一个描述AOP程序的结构类ServiceProxy
package cn.mldn.aop;
public class ServiceProxy {
public void beforeMethod() {
System.out.println("####### 【ServiceProxy】public void beforeMethod(){}");
}
public void afterMethod() {
System.out.println("####### 【ServiceProxy】public void afterMethod(){}");
}
}
4,配置applicationContext.xml文件:
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config />
<context:component-scan base-package="cn.mldn" />
<!-- 如果要想让切面控制有效,那么必须将此类的对象交由Spring进行管理 -->
<bean id="serviceProxy" class="cn.mldn.aop.ServiceProxy"/>
<!-- 要求进入到AOP的配置,重点配置切入点,以及确定切入的处理操作方法 -->
<aop:config>
<aop:pointcut expression="execution(* cn.mldn.service..*.*(..))" id="pointCut"/>
<aop:aspect ref="serviceProxy"> <!-- 进行切面的配置,如果是切面控制应该有一个控制的类 -->
<!-- 不同的切面处理操作可以使用同一个切入点,或者每一个操作来定义属于自己的切入点 -->
<aop:before method="beforeMethod" pointcut-ref="pointCut"/>
<aop:after method="afterMethod" pointcut="execution(* cn.mldn.service..*.*(..))"/>
</aop:aspect>
</aop:config>
</beans>
5,定义测试类
package cn.mldn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mldn.service.IMemberService;
public class TestMember {
public static void main(String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
IMemberService ms = ctx.getBean("memberServiceImpl",
IMemberService.class);
ms.delete("mldn");
}
}
运行结果: