[Spring]一步步实现Spring AOP(一)

来源:互联网 发布:搞笑淘宝买家丝袜秀 编辑:程序博客网 时间:2024/05/16 17:24

首先查看一下项目结构
aop

下面是Service接口与实现类

public interface Service {    /**     * 添加方法     */    public void add ();}
public class ServiceImpl implements Service{    /**     * 添加方法     */    @Override    public void add (){        System.out.println("Service调用add()方法,插入数据库数据。");    }}

配置通知类

/** * 切面 * @author dou * */public class Aop implements MethodBeforeAdvice,AfterReturningAdvice{    @Override    public void afterReturning(Object arg0, Method arg1, Object[] arg2,            Object arg3) throws Throwable {        System.out.println("AOP----结束事务,close。");    }    @Override    public void before(Method arg0, Object[] arg1, Object arg2)            throws Throwable {        System.out.println("AOP----开启事务,准备进行CRUD。");    }  }

XML文件配置

    <!-- 注入切面 -->    <bean id="aopDemo" class="com.aop.Aop"></bean>    <!-- 注入Service -->    <bean id="serviceDemo" class="com.service.ServiceImpl"></bean>    <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">          <!-- 代理接口 -->        <property name="proxyInterfaces">            <value>com.service.Service</value>            <!-- <value></value> -->        </property>        <!-- 指定拦截器(通知) -->        <property name="interceptorNames">              <list>                  <value>aopDemo</value>               </list>          </property>         <!-- 配置被代理对象 -->          <property name="target" ref="serviceDemo"></property>    </bean>

Test测试类

    public static void main(String[] args) {        ApplicationContext context =                 new ClassPathXmlApplicationContext("spring.xml");        Service service = (Service) context.getBean("proxyFactoryBean");        service.add();    }
1 0
原创粉丝点击