java框架学习日志-10(自定义类实现AOP)

第二种实现方式——自定义实现

经过springAPI来实现须要经过实现接口或者继承来构建关注点。自定义实现的话就不须要了。Log代码以下java

public class Log {
    public void before(){
        System.out.println("——————方法执行前");
    }
    public void after(){
        System.out.println("——————方法执行后");
    }

}

Service和ServiceImpl代码不变。spring

public interface Service {
    public void add();
    public void update();
    public void delete();
    public void search();

}

public class ServiceImpl implements Service{
    @Override
    public void add() {
        System.out.println("增长用户");
    }

    @Override
    public void update() {
        System.out.println("修改用户");
    }

    @Override
    public void delete() {
        System.out.println("删除用户");
    }

    @Override
    public void search() {
        System.out.println("查询用户");
    }
}

beans配置修改以下。在aop:config里增长aop:aspect,ref是关联的关注点。aop:pointcut一样是切入点。befor和after对应前置通知和后置通知。express

<?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-2.5.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <bean id="service" class="ServiceImpl"/>
    <bean id="log" class="Log"/>
    <aop:config>
        <aop:aspect ref="log">
            <aop:pointcut id="pointcut" expression="execution(* ServiceImpl.*(. .))"/>
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>

    </aop:config>

</beans>

测试以下
ide

相关文章
相关标签/搜索