spring的学习_____10 spring AoP的实现方式3 使用 注解 实现

(本案例是idea下的maven项目,补充上一篇文章)

1.编写加了注解的增强类:

@Aspect
//类 --切面
public class Anno {

    @Before("execution(* com.xbf.service.UserServiceImpl.*(..))")
    //注解声明:切入点,和要织入进去的方法
    public void before(){
        System.out.println("方法执行前:~~~~~~~~~~~~~~");
    }

    @After("execution(* com.xbf.service.UserServiceImpl.*(..))")
    //注解声明:切入点,和要织入进去的方法
    public void after(){
        System.out.println("方法执行后~~~~~~~~~~~~~~");
    }


}

2.spring的配置文件 dnno.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: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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--1.User bean的注册-->
    <bean id="user" class="com.xbf.service.UserServiceImpl"/>

    <!--2.增强类的注册-->
    <bean id="anno" class="com.xbf.anno.Anno"/>

    <!--识别注解 自动代理-->
    <aop:aspectj-autoproxy/>



</beans>

3.测试类的编写:

public class Anno {

    @Test
    public void test(){

        ApplicationContext context=new ClassPathXmlApplicationContext("anno.xml");

        UserService user = (UserService) context.getBean("user");

        user.add();

    }
}

总结:增强类添加了注解; 在类名上面添加 切面的注解,在类中的方法名上面添加 织入时机的注解(并声明切入点,切入点就是要织入的接口实现类的目标方法)。

猜你喜欢

转载自www.cnblogs.com/xbfchder/p/11273034.html