你的位置:首页 > Java教程

[Java教程]Spring中的增强


在Spring中,目前我学习了几种增强的方式,和大家分享一下

一:前置增强和后置增强

源码介绍:

1.User.java

package cn.zhang.entity;public class User {  private Integer id; // 用户ID  private String username; // 用户名  private String password; // 密码  private String email; // 电子邮件  public Integer getId() {    return id;  }  public void setId(Integer id) {    this.id = id;  }  public String getUsername() {    return username;  }  public void setUsername(String username) {    this.username = username;  }  public String getPassword() {    return password;  }  public void setPassword(String password) {    this.password = password;  }  public String getEmail() {    return email;  }  public void setEmail(String email) {    this.email = email;  }  }

View Code

2.IDao.java

package cn.zhang.dao;//定义接口import cn.zhang.entity.User;public interface IDao {  //定义方法  public void save(User user);}

View Code

3.UserDao.java

package cn.zhang.dao.impl;//实现接口import cn.zhang.dao.IDao;import cn.zhang.entity.User;public class UserDao implements IDao {  @Override  //实现方法  public void save(User user) {    System.out.println("save success!");      }}

View Code

4.IUserBiz.java

package cn.zhang.biz;//业务接口import cn.zhang.entity.User;public interface IUserBiz {  //待处理的方法   public void save(User user);}

View Code

5.UserBiz.java

package cn.zhang.biz.impl;//业务接口的实现类import cn.zhang.biz.IUserBiz;import cn.zhang.dao.IDao;import cn.zhang.entity.User;public class UserBiz implements IUserBiz {  //引入IDao接口  private IDao dao;  @Override  //实现方法  public void save(User user) {    dao.save(user);  }  //dao 属性的setter访问器,会被Spring调用,实现设值注入  public IDao getDao() {    return dao;  }  public void setDao(IDao dao) {    this.dao = dao;  }}

View Code

6.LoggerAfter.java(后置增强)

package cn.zhang.aop;//后置增强import java.lang.reflect.Method;import org.springframework.aop.AfterReturningAdvice;public class LoggerAfter implements AfterReturningAdvice {  @Override  public void afterReturning(Object arg0, Method arg1, Object[] arg2,      Object arg3) throws Throwable {      System.out.println("后置增强代码");      }}

View Code

7.LoggerBefore.java(前置增强)

package cn.zhang.aop;//前置增强import java.lang.reflect.Method;import org.apache.log4j.Logger;import org.springframework.aop.MethodBeforeAdvice;public class LoggerBefore implements MethodBeforeAdvice {  private static final Logger log = Logger.getLogger(LoggerBefore.class);  @Override  public void before(Method arg0, Object[] arg1, Object arg2)      throws Throwable {    log.info("前置内容AAA");      System.out.println("前置增强代码");  }}

View Code

8.applicationContext.

<??><beans ="http://www.springframework.org/schema/beans"  ="http://www.w3.org/2001/ ="http://www.springframework.org/schema/aop"  ="http://www.springframework.org/schema/p"  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-4.1.xsd    ">  <bean id="dao" class="cn.zhang.dao.impl.UserDao" />  <bean id="biz" class="cn.zhang.biz.impl.UserBiz">    <property name="dao" ref="dao"></property>  </bean>  <!-- 定义前置增强组件 -->  <bean id="loggerBefore" class="cn.zhang.aop.LoggerBefore" />  <!-- 定义后置增强组件 -->  <bean id="loggerAfter" class="cn.zhang.aop.LoggerAfter" />  <!-- 针对AOP的配置 -->  <aop:config>    <aop:pointcut id="pointcut"      expression="execution(public void save(cn.zhang.entity.User))" />    <!-- 将增强处理和切入点结合在一起,在切入点处插入增强处理,完成"织入" -->    <aop:advisor pointcut-ref="pointcut" advice-ref="loggerBefore" />    <aop:advisor pointcut-ref="pointcut" advice-ref="loggerAfter" />  </aop:config></beans> 

View Code

9.MyTest.java

package cn.zhang.test;//测试类import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathimport cn.zhang.biz.IUserBiz;import cn.zhang.entity.User;public class MyTest {public static void main(String[] args) {    ApplicationContext ctx = new ClassPath);  IUserBiz biz=(IUserBiz)ctx.getBean("biz");  User user=new User();  biz.save(user);  System.out.println("success!");}}

View Code

10.log4j.properties(日志的配置文件)

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=c\:mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=info, stdout

View Code

当然,别忘了引入我们需要的jar包啊!

常用的jar:

 

二:异常抛出增强和环绕增强

源码介绍:

1.User.java

package cn.zhang.entity;public class User {  private Integer id; // 用户ID  private String username; // 用户名  private String password; // 密码  private String email; // 电子邮件      public User() {    super();    // TODO Auto-generated constructor stub  }    public User(Integer id, String username, String password, String email) {    super();    this.id = id;    this.username = username;    this.password = password;    this.email = email;  }  public Integer getId() {    return id;  }  public void setId(Integer id) {    this.id = id;  }  public String getUsername() {    return username;  }  public void setUsername(String username) {    this.username = username;  }  public String getPassword() {    return password;  }  public void setPassword(String password) {    this.password = password;  }  public String getEmail() {    return email;  }  public void setEmail(String email) {    this.email = email;  }  }

View Code

2.UserService.java

package cn.zhang.service;public class UserService {  public void delete() {    //int i = 5 / 0;//制造一个错误,用于测试异常抛出增强    System.out.println("delete success!");  }}

View Code

3.ErrorLog.java(异常抛出增强)

package cn.zhang.aop;//异常抛出增强import java.lang.reflect.Method;import org.apache.log4j.Logger;import org.springframework.aop.ThrowsAdvice;public class ErrorLog implements ThrowsAdvice {  private static final Logger log = Logger.getLogger(ErrorLog.class);  public void afterThrowing(Method method, Object[] args, Object target,      RuntimeException e){    log.error(method.getName() + " 方法发生异常:" + e);  }}

View Code

4.AroundLog(环绕增强)

package cn.zhang.aop;//环绕增强import java.lang.reflect.Method;import java.util.Arrays;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;import org.apache.log4j.Logger;public class AroundLog implements MethodInterceptor {    private static final Logger log = Logger.getLogger(AroundLog.class);  @Override  public Object invoke(MethodInvocation invocation) throws Throwable {      Object target=invocation.getThis();//获取被代理对象    Method method = invocation.getMethod();//获得被代理方法    Object[] args = invocation.getArguments();//获得方法参数        System.out.println("调用"+target+"的"+method.getName()+"方法。方法参数:"+Arrays.toString(args));    Object result;//调用目标方法,获取目标方法返回值    try {      result = invocation.proceed();      System.out.println("调用" + target + "的" + method.getName()          + "方法。方法返回值:" + result);      return result;    } catch (Exception e) {      log.error(method.getName()+"方法发生异常:"+e);      throw e;    }      }}

View Code

5.applicationContext.

<??><beans ="http://www.springframework.org/schema/beans"  ="http://www.w3.org/2001/   ="http://www.springframework.org/schema/aop"  ="http://www.springframework.org/schema/p"  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-4.1.xsd    ">  <bean id="service" class="cn.zhang.service.UserService" />  <!-- 异常抛出增强 -->  <!-- <bean id="error" /> -->  <!-- 环绕增强 -->  <bean id="error" class="cn.zhang.aop.AroundLog"/>    <aop:config>    <aop:pointcut expression="execution(public void delete())"      id="pointcut" />    <aop:advisor advice-ref="error" pointcut-ref="pointcut" />  </aop:config></beans> 

View Code

6.MyTest.java

package cn.zhang.test;//测试类import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathimport cn.zhang.service.UserService;public class MyTest {  public static void main(String[] args) {        ApplicationContext ctx = new ClassPath"applicationContext.);    UserService service = (UserService) ctx.getBean("service");    try {      service.delete();    } catch (Exception e) {      System.out.println("错误了");    }    System.out.println("success!");  }}

View Code

三:注解增强方式实现前置增强和后置增强

源码介绍:

1.UserService.java

package cn.service;//业务处理类public class UserService {  //方法  public void delete() {    System.out.println("delete success!");  }}

View Code

2.AnnotationAdvice.java(注解增强)

package cn.aop;//注解增强import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class AnnotationAdvice {    // 定义前置增强  @Before("execution(* cn.service.UserService.*(..))")  public void before(JoinPoint jp) {    System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,参数:"+jp.getArgs()+",参数个数:"+jp.getArgs().length);    System.out.println("before");  }  // 定义后置增强  @AfterReturning(pointcut="execution(* cn.service.UserService.*(..))",returning="returnValue")  public void afterReturning(JoinPoint jp,Object returnValue) {     System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,参数:"+jp.getArgs()+",返回值为:"+returnValue);    System.out.println("after");  }}

View Code

注:

java.lang.Object[] getArgs():获取连接点方法运行时的入参列表
Signature getSignature() :获取连接点的方法签名对象
java.lang.Object getTarget() :获取连接点所在的目标对象
java.lang.Object getThis() :获取代理对象本身

3.applicationContext.

<?  ="http://www.w3.org/2001/  ="http://www.springframework.org/schema/p"  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-4.1.xsd    ">      <bean id="service" class="cn.service.UserService" />  <bean id="error" class="cn.aop.AnnotationAdvice" />  <!-- 针对AOP的配置 -->  <aop:aspectj-autoproxy /></beans> 

View Code

4.MyTest.java

package cn.test;//注解增强测试import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathimport cn.service.UserService;public class MyTest {  public static void main(String[] args) {    ApplicationContext ctx = new ClassPath);    UserService biz=(UserService)ctx.getBean("service");    biz.delete();    System.out.println("success!");  }}

View Code