比如现在我们希望对这个学生对象的study方法进行增强,在不修改源代码的情况下,增加一些额外的操作:

public class Student {
    public void study(){
        System.out.println("室友还在打游戏,我狠狠的学Java,太爽了"); 
      	//现在我们希望在这个方法执行完之后,打印一些其他的内容,在不修改原有代码的情况下,该怎么做呢?
    }
}
<bean class="org.example.entity.Student"/>

那么我们按照上面的流程,依次来看,首先需要解决的问题是,找到需要切入的类,很明显,就是这个Student类,我们要切入的是这个study方法。

接着声明新类 StudentAOP,并将其注册为Bean:

public class StudentAOP {
  	//这个方法就是我们打算对其进行的增强操作
    public void afterStudy() {
        System.out.println("为什么毕业了他们都继承家产,我还倒给他们打工,我努力的意义在哪里...");
    }
}

配置 Spring AOP 配置文件,实现插入在原代码后面执行:

<aop:config>
	<aop:pointcut id="test" expression="execution(* org.example.entity.Student.study())"/>
	<aop:aspect ref="studentAOP">
            <aop:after pointcut-ref="test" method="afterHello"/>
        </aop:aspect>
</aop:config>

调用原方法即可:

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
    Student bean = context.getBean(Student.class);
    bean.study();
}