spring AOP 示例

来源:互联网 发布:c十十语言范磊视频教程 编辑:程序博客网 时间:2024/05/17 23:54

不说原理,不说框架,拿起键盘就是撸,Ctrl+c,Ctrl+v,就是干!
(原理请移步百度)

配置文件中:

    <context:component-scan base-package="com.saike.aop"/>    <aop:aspectj-autoproxy proxy-target-class="true"/>    <bean id="noticeService" class="com.saike.service.impl.NoticeServiceImpl"/>

代码:

import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;import java.util.HashMap;import java.util.Map;@Component@Aspectpublic class NoticeAop {    private Logger logger = Logger.getLogger(NoticeAop.class);    @Pointcut("execution(* com.saike.service.impl.NoticeServiceImpl.insert(..))")    public void execudeService() {    }    @Before("execution(* com.saike.service.impl.NoticeServiceImpl.insert(..))")    public void before() {        System.out.println("###### before ######");    }    @After("execution(* com.saike.service.impl.NoticeServiceImpl.insert(..))")    public void after() {        System.out.println("####  after ###");    }    /**     * 获取返回值     * @param returnVal     */    @AfterReturning(pointcut = "execution(* com.saike.service.impl.NoticeServiceImpl.insert(..))", returning = "returnVal")    public void afterOperation(Object returnVal) {        logger.debug("####### afterReturning start #######");        Map<String, String> map = (HashMap<String, String>) returnVal;        if (map != null && map.containsKey("msg") && "success".equals(map.get("msg"))) {            logger.debug("###### msg === " + map.get("msg"));        }    }}

注意:

[1] - 在xml中配置。

[2] - 添加@Component、@Aspect 注解。

0 0
原创粉丝点击