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

首先查看一下项目结构
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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值