spring AOP详解之--前置增强 (MethodBeforeAdvice)



这里举一个简单的demo

 
  先写一个接口 Hello.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());
    }
}

这就是一个完整的前置增强的例子,后面我还会陆续介绍其他几种增强。谢谢
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值