Spring AOP与IOC以及自定义注解

来源:互联网 发布:高收益网络国债信托 编辑:程序博客网 时间:2024/05/22 15:38

Spring AOP实现日志服务


pom.xml需要的jar

<dependency>    <groupId>org.apache.commons</groupId>    <artifactId>commons-lang3</artifactId>    <version>3.4</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>4.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>4.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.2.4.RELEASE</version></dependency><dependency><groupId>cglib</groupId><artifactId>cglib-nodep</artifactId><version>3.2.0</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.8</version></dependency><dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.2</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency>


一.AOP用法一配置XML

1.Before Advice

Before Advice会在目标方法执行之前被调用,可以通过实现org.springframework.aop.MethodBeforeAdvice接口实现。

LogBeforeAdvice.java

package com.blog.csdn.net.unix21;import java.lang.reflect.Method;import java.util.logging.Level;import org.springframework.aop.MethodBeforeAdvice;import java.util.logging.Logger;/** * * @author http://blog.csdn.net/unix21/ */public class LogBeforeAdvice implements MethodBeforeAdvice {    private Logger logger=Logger.getLogger(this.getClass().getName());    public void before(Method method,Object[] args,Object target) throws Throwable{        logger.log(Level.INFO,"日志信息>>>method starts..."+method);    }}


beans-config.xml配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"     xmlns:aop="http://www.springframework.org/schema/aop" 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:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="              http://www.springframework.org/schema/beans              http://www.springframework.org/schema/beans/spring-beans-4.0.xsd              http://www.springframework.org/schema/context              http://www.springframework.org/schema/context/spring-context-4.0.xsd             http://www.springframework.org/schema/mvc              http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd           http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <bean id="LogBeforeAdvice" class="blog.csdn.net.unix21.LogBeforeAdvice"/><bean id="HelloSpeaker" class="blog.csdn.net.unix21.HelloSpeake"/><bean id="HelloProxy" class="org.springframework.aop.framework.ProxyFactoryBean">    <property name="proxyInterfaces" value="blog.csdn.net.unix21.IHello"/>    <property name="target" ref="HelloSpeaker"/>    <property name="interceptorNames">        <list>            <value>LogBeforeAdvice</value>        </list>    </property></bean></beans>

接口

IHello.java

package blog.csdn.net.unix21;public interface IHello {public void hello(String name);}

HelloSpeaker.java

package blog.csdn.net.unix21;public class HelloSpeaker implements IHello {public void hello(String name){System.out.println("Hello, "+name);}}


测试Before Advice

SpringAOP 前置增强 后置增强 编程式 需XML配置

  ApplicationContext context=new ClassPathXmlApplicationContext("beans-config.xml");  IHello h=(IHello)context.getBean("helloProxy");  h.hello("blog.csdn.net.unix21")


运行成功使用AOP的方式打印日志信息:


参考:《Spring 2.0技术手册》

Spring 3.1编写AOP时需要导入的倚赖jar包汇总

菜鸟学SSH(七)——Spring jar包详解


2.After Advice

After Advice会在目标方法执行之后被调用,可以通过实现org.springframework.aop.AfterReturningAdvice接口来实现

import java.lang.reflect.Method;import java.util.logging.Level;import java.util.logging.Logger;import org.springframework.aop.AfterReturningAdvice;public class LogAfterAdvice  implements AfterReturningAdvice  {private Logger logger=Logger.getLogger(this.getClass().getName());    public void afterReturning(Object object, Method method, Object[] args, Object target) throws Throwable {       logger.log(Level.INFO,"日志信息<<<method ends..."+method);    }  }

修改beans-config.xml配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"     xmlns:aop="http://www.springframework.org/schema/aop" 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:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="              http://www.springframework.org/schema/beans              http://www.springframework.org/schema/beans/spring-beans-4.0.xsd              http://www.springframework.org/schema/context              http://www.springframework.org/schema/context/spring-context-4.0.xsd             http://www.springframework.org/schema/mvc              http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd           http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <bean id="LogBeforeAdvice" class="blog.csdn.net.unix21.LogBeforeAdvice"/><bean id="HelloSpeaker" class="blog.csdn.net.unix21.HelloSpeake"/><bean id="HelloProxy" class="org.springframework.aop.framework.ProxyFactoryBean">    <property name="proxyInterfaces" value="blog.csdn.net.unix21.IHello"/>    <property name="target" ref="HelloSpeaker"/>    <property name="interceptorNames">        <list>            <value>LogBeforeAdvice</value><value>LogAfterAdvice</value>        </list>    </property></bean></beans>


成功的执行了LogAfterAdvice


二.AOP用法二编程式不配置XML

SpringAOP 前置增强 后置增强 编程式 无需XML配置

ProxyFactory pf=new ProxyFactory();pf.setTarget(new TestModel());pf.addAdvice(new LogBeforeAdvice());pf.addAdvice(new LogAfterAdvice());TestModel gt=(TestModel)pf.getProxy();return gt.add(...);
效果是一样的。


三.Java自定义注解和运行时靠反射获取注解

还是日志信息,我们希望运行的时候可以获取自定义注解

import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到  @Target({ElementType.FIELD,ElementType.METHOD})//定义注解的作用目标**作用范围字段、枚举的常量/方法  @Documented//说明该注解将被包含在javadoc中 public @interface FieldMeta {    /**      * 是否为序列号      * @return      */      boolean id() default false;      /**      * 字段名称      * @return      */      String name() default "";      /**      * 是否可编辑      * @return      */      boolean editable() default true;      /**      * 是否在列表中显示      * @return      */      boolean summary() default true;      /**      * 字段描述      * @return      */      String description() default "";      /**      * 排序字段      * @return      */      int order() default 0;  }


声明注解



需要注意如果一个类是接口的实现,那么这种注解需要写接口方法上,例如AOP的调用方式一,对于AOP的调用方式二可以把注解写类的方法上即可。


调用

if (method.isAnnotationPresent(FieldMeta.class)) {FieldMeta myAnnotation = method.getAnnotation(FieldMeta.class);System.out.println("注解:" + myAnnotation.description() + " 类:"+target.getClass().getName()+" 方法:" + method.getName());}




参考:Java自定义注解和运行时靠反射获取注解



0 0
原创粉丝点击