spring aop demo

2017-06-22

56

0

技术:spring+ aop

运行环境:IDEA 15.2 + jdk8 + windows 7

demo功能:将spring aop功能应用到实际代码场景代码demo。 这里主要举例在调用一个方法前, 记录这个方法的方法名和所在类的类名

并且修改这个方法的返回

新建aop注解类

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Loggable {
    String className() default "";//记录类名
    String methodName() default "";//记录方法名
}

新建aop 切点类

@Aspect//这个注解需要开启 
public class LoggerAspect {
    @Around(value = "execution(* com.yuewen.test3..*.*(..)) && @annotation(loggable)")
    public Object around(ProceedingJoinPoint join, Loggable loggable) throws Throwable {
        System.out.println("class name=" + loggable.className() + ", method name=" + loggable.methodName());//打印类名 方法名
        join.proceed();
        return "12312312";//修改方法调用的返回, 每次调用都返回这个, 不返回真实方法产生的结果(join.proceed())
    }
}

新建服务类

@Component
public class UserService {
    @Loggable(className = "UserService", methodName = "getById")//表示调用这个方法需要走aop过程
    public String getById(long id) {
        return "francis";//由于aop中修改了返回, 这个francis 永远不会返回
    }
}

添加spring 配置文件

 <?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-2.5.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <bean id="logService" class="com.yuewen.test3.LoggerAspect"></bean>
    <context:component-scan base-package="com.yuewen.test3"></context:component-scan>
</beans>

测试代码和结果

@Test
public void test3() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
UserService bean = (UserService) context.getBean(UserService.class);
System.out.println(bean.getById(1111));//本来该返回francis, 但是没有哦, 自己思考下为啥
}

结果
六月 22, 2017 4:19:46 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2a3046da: startup date [Thu Jun 22 16:19:46 GMT+08:00 2017]; root of context hierarchy
六月 22, 2017 4:19:46 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean3.xml]
class name=UserService, method name=getById
12312312

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think