3.2.1 明确需求
在某个方法上加上@FddLog,就会在执行这个方法的前后,自动输出相应的信息。下面以把大象放进冰箱为例子进行演示:
3.2.2 基本接口和实现
- public interface ElephentToRe{
- public void toRe();
- }
实现类如下:
- public class ElephentToReImpl implements ElephentToRe{
- public void toRe() {
- System.out.println("把大象放冰箱");
- }
- }
3.2.3 定义切面和通知
- public class ElephentToReHelper{
- public void beforeElephentToRe(){
- System.out.println("把冰箱门打开");
- }
- public void afterElephentToRe(){
- 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" 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="elephentToReHelper" class="com.fdd.bean.ElephentToReHelper"></bean>
- <!— 定义被代理者 –>
- <bean id="elephentToReImpl" class="com.fdd.bean.ElephentToReImpl"></bean>
- <aop:config>
- <aop:aspect ref="elephentToReHelper">
- <aop:before method="beforeElephentToRe" pointcut="execution(* *.toRe(..))" />
- <aop:after method="afterElephentToRe" pointcut="execution(* *.toRe(..))" />
- </aop:aspect>
- </aop:config>
- </beans>
3.2.4 测试看效果
- public class Test {
- public static void main(String[] args){
- @SuppressWarnings("resource")
- ApplicationContext appCtx = new FileSystemXmlApplicationContext("application.xml");
- ElephentToRe elephentToReImpl = (ElephentToRe)appCtx.getBean("elephentToReImpl");
- elephentToReImpl.toRe();
- }
- }
上面的这种方法是通过纯粹的POJO切面来完成的。实现方式也比较简单。
4 我对AOP思想的看法
任何新技术的出现都是为了解决目前开发中存在的某些痛点。对于aop来说,其主要是把一些功能代码进行抽象封装,和主业务逻辑代码进行剥离。在需要的地方进行织入即可。
我的看法是
(1)在平时开发代码的时候,完全可以把一些常见的,常用的功能代码进行封装,尽量做到动态配置。不同的功能模块只需要进行织入即可。
(2)定义业务逻辑的模板,比如说如果要解决某一个业务功能,如果页面类似,可以按照基本的框架进行组合,然后使用配置平台进行可控化配置即可。