AOP第一个例子

一.什么是AOP?

AOP  aspect overied programming  面向切面编程

AOP的目标  “让我们可以专心做事”

AOP原理:1.将复杂的需求分解出不同方面,将散布在系统中的公共功能集中解决

     2.采用代理机制组装起来运行,在不改变原程序的基础上,对代码进行增强处理,增加新的功能

· Spring 切面可应用的 5 种通知类型:

1. Before——在方法调用之前调用通知

2. After——在方法完成之后调用通知,无论方法执行成功与否  

3. After-returning——在方法执行成功之后调用通知

4. After-throwing——在方法抛出异常后进行通知

5. Around——通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为

下边是AOP的一个案例,在不改变原代码的情况下,在输出的结果前加一行输出结果:

实现步骤如下:

1.定义一个类实现MethodBeforeAdvice接口

public class LoggerBefore implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("前边记录日志");
    }
}

2.创建一个service层,然后实现,并把这里获得的Dao接口的对象进行封装

public interface IHelloService {
    public void some();
}
public class IHelloServiceImpl implements IHelloService {
    IHelloDao dao;

    public IHelloDao getDao() {
        return dao;
    }

    public void setDao(IHelloDao dao) {
        this.dao = dao;
    }

    public void some() {
        dao.getSomething();
    }
}

3.书写applicationContext.xml中的节点,引入aop的路径

xmlns:aop="http://www.springframework.org/schema/aop"
  //这里结果是在输出结果之前加入需要加入的效果
<bean id="before" class="Before.LoggerBefore"></bean> <aop:config> <!--<aop:pointcut id="mypoint" expression="execution(* *.service.*(..))"></aop:pointcut>--> <aop:pointcut id="mypoint" expression="execution(* service.*.*(..))"></aop:pointcut> <aop:advisor advice-ref="before" pointcut-ref="mypoint"></aop:advisor> </aop:config>

4.测试类代码

    //AOP
    @Test
    public void Test03(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext04Aop.xml");
        IHelloService service = (IHelloService)context.getBean("service");
        service.some();
    }
输出结果:成功的在之前加入了需要加入的东西,在没有改变原代码的前提下
 
原文地址:https://www.cnblogs.com/1234AAA/p/8510392.html