这里举一个简单的demo
先写一个接口 Hello.java
最后的xml文件的配置
再编写一个测试类TestHello.java
这就是一个完整的前置增强的例子,后面我还会陆续介绍其他几种增强。谢谢
package niit.soft1521; /** * Created by lenovo-pc on 2017/3/13. */ public interface Hello { String sayHello(); }在写一个接口的实施类HelloImpl.java
package niit.soft1521; /** * Created by lenovo-pc on 2017/3/13. */ public class HelloImpl implements Hello { @Override public String sayHello() { return "hello ,welcom !"; } }再写一个前置增强的类MyBeforeMethod.java
package niit.soft1521; /** * Created by lenovo-pc on 2017/3/13. * 用户自定义的前置增强类 */ public class MybeforeMethod { public void BeforeMethod(){ System.out.println("this is a before method !"); } }
最后的xml文件的配置
<?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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="hello" class="niit.soft1521.HelloImpl"></bean> <bean id="MyBefore" class="niit.soft1521.MybeforeMethod"></bean> <aop:config> <aop:aspect id="before" ref="MyBefore"> <aop:pointcut id="MyPointCut" expression="execution(* niit.soft1521.*.*(..))"></aop:pointcut> <aop:before method="BeforeMethod" pointcut-ref="MyPointCut"></aop:before> </aop:aspect> </aop:config> </beans>
再编写一个测试类TestHello.java
package niit.soft1521; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by lenovo-pc on 2017/3/13. */ public class TestHello { public static void main(String[] args) { ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml"); Hello hello=(Hello)applicationContext.getBean("hello"); System.out.println(hello.sayHello()); } }
这就是一个完整的前置增强的例子,后面我还会陆续介绍其他几种增强。谢谢