SpringAOP简单实例(基于注解)

首先,在ApplicationContext.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context
                 http://www.springframework.org/schema/context/spring-context.xsd
                 http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--    <bean id="bunShop" class="com.day10_24.dao.daoImpl.BunShopImpl"></bean>-->

    <!--    <bean id="shopService" class="com.day10_24.service.serviceImpl.BunShopServiceImpl">-->
    <!--        <property name="bunShop" ref="bunShop"></property>-->

    <!--    </bean>-->

<!--   开启基于注解的配置    -->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
<!--   注解配置要扫描的包   -->
    <context:component-scan base-package="com.day10_24"></context:component-scan>

</beans>

 然后编写AOP切面类

        

package com.day10_24.AOPs;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class Aop {

     <!--  execution后面的为要增强的方法的路径以及参数的设定,可使用通配符  -->
    @Pointcut("execution(* com.day10_24.AOPs.IUserDaoImpl.sys())")
    public void testPoint(){
    }

    @Before("testPoint()")
    public void testBefore()
    {
        System.out.println("testPoint() Before Success!");
    }

    @After("testPoint()")
    public void testAfter()
    {
        System.out.println("testPoint() After Success!");
    }

}

 接下来编写目标对象方法

package com.day10_24.AOPs;

public interface IUserDao {
    public void sys();

}

 

package com.day10_24.AOPs;

import org.springframework.stereotype.Component;

@Component("iUserDaoImpl")
public class IUserDaoImpl implements IUserDao {
    @Override
    public void sys() {
        System.out.println("hello World!");
    }
}

 编写测试类

public class Test3 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext=
                new ClassPathXmlApplicationContext("applicationContext.xml");
        IUserDao userDao=applicationContext.getBean("iUserDaoImpl", IUserDaoImpl.class);
        userDao.sys();
    }
}

 打印结果:

             

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值