Home > Java > javaTutorial > body text

Examples to explain AOP implementation in Java's Spring framework

高洛峰
Release: 2017-01-23 10:41:46
Original
1292 people have browsed it

Introduction
Aspect-oriented programming (AOP) provides another perspective to think about program structure. In this way, it makes up for the shortcomings of object-oriented programming (OOP). In addition to classes, AOP provides aspects. Aspects modularize concerns, such as transaction management across multiple types and objects. (The terminology for these concerns is often called crosscutting concerns.)

A key component of Spring is the AOP framework. Nonetheless, the Spring IoC container does not rely on AOP, which means you are free to choose whether to use AOP or not. AOP provides powerful middleware solutions, which makes the Spring IoC container more complete.

Spring 2.0 AOP:

Spring 2.0 introduces a simpler and more powerful way to customize aspects. Users can choose to use a schema-based approach or use @AspectJ annotation. For new applications, we recommend users to use the @AspectJ style if they are developed using Java 5, otherwise they can use the pattern-based style. Both styles fully support advice types and AspectJ's pointcut language, although they still use Spring AOP for weaving.

This chapter mainly discusses Spring 2.0's support for pattern-based and @AspectJ-based AOP. Spring 2.0 fully retains backward compatibility with Spring 1.2. The next chapter will discuss the underlying AOP support provided by the Spring 1.2 API.

AOP used in Spring:

Provides declarative enterprise services, especially to replace EJB declarative services. The most important service is declarative transaction management, which is built on Spring's transaction abstraction.

Allows users to implement customized aspects and use AOP to improve the use of OOP.

Examples
We often use the following types
1, proxy-based AOP
2, pure simple java object aspect
3, @Aspect annotation form
4. Injection form of Aspcet aspects
Let’s apply them one by one.
Let’s first write a few basic classes.
Interface class:

/** 
 * 定义一个接口 
 */
public interface Sleepable { 
  
  /** 
   * 睡觉方法 
   */
  void sleep(); 
}
Copy after login

Implementation class:

/**
 * 本人实现睡觉接口
 */
public class ChenLliNa implements Sleepable {
  
  @Override
  public void sleep() {
    // TODO Auto-generated method stub
    System.out.println("乖,该睡觉了!");
  }
}
Copy after login

Enhancement class:

/**
 * 定义一个睡眠的增强 同时实现前置 和后置
 */
public class SleepHelper implements MethodBeforeAdvice, AfterReturningAdvice {
  
  @Override
  public void afterReturning(Object returnValue, Method method,
      Object[] args, Object target) throws Throwable {
     System.out.println("睡觉前要敷面膜");
  }
  
  @Override
  public void before(Method method, Object[] args, Object target)
      throws Throwable {
    System.out.println("睡觉后要做美梦");
  }
  
}
Copy after login


1. Agent-based AOP

<!-- 创建一个增强 advice -->
  <bean id ="sleepHelper" class="com.tgb.springaop.aspect.SleepHelper"/>
  
  <bean id="lina" class="com.tgb.springaop.service.impl.ChenLliNa"/>
  <!-- 定义切点  匹配所有的sleep方法-->
  <bean id ="sleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
      <property name="pattern" value=".*sleep"></property>
  </bean>
    
  <!-- 切面  增强+切点结合 -->
  <bean id="sleepHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
     <property name="advice" ref="sleepHelper"/>
     <property name="pointcut" ref="sleepPointcut"/>
  </bean>
    
  <!-- 定义代理对象 -->
  <bean id="linaProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
      <property name="target" ref="lina"/>
      <property name="interceptorNames" value="sleepHelperAdvisor"/>
      <!-- <property name="proxyInterfaces" value="com.tgb.springaop.service.Sleepable"/> -->
  </bean>
Copy after login

For example, in the configuration file:
The pattern attribute specifies a regular expression, which matches all sleep methods
The purpose of using org.springframework.aop.support.DefaultPointcutAdvisor is to make pointcuts Combined with enhancement to form a complete aspect
After the final configuration, a final proxy object is generated through org.springframework.aop.framework.ProxyFactoryBean.

2. Pure and simple java object aspect
How to say pure and simple java object aspect? In my opinion, compared to the first configuration, there is no need to use a proxy, but through spring. The internal mechanism automatically scans. At this time, our configuration file should be modified as follows:

<!-- 创建一个增强 advice -->
<bean id ="sleepHelper" class="com.tgb.springaop.aspect.SleepHelper"/>
<!-- 目标类 -->
<bean id="lina" class="com.tgb.springaop.service.impl.ChenLliNa"/>
  
<!-- 配置切点和通知-->
<bean id ="sleepAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
   <property name="advice" ref="sleepHelper"></property>
   <property name="pattern" value=".*sleep"/>
</bean>
  
<!-- 自动代理配置 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
Copy after login

Is it much simpler than the first one? There is no need to configure the proxy.

3. @Aspect annotation form
According to our experience, we know that the annotation form is simpler than the configuration file. At this time, you need to annotate the existing method or class:

/**
 * 通过注解的方式 添加增强
 */
@Aspect
@Component
public class SleepHelper03 {  
    
  /*@Pointcut("execution(* com.tgb.springaop.service.impl..*(..))")*/
  @Pointcut("execution(* *.sleep(..))")
  public void sleeppoint(){}
    
  @Before("sleeppoint()")
  public void beforeSleep(){
    System.out.println("睡觉前要敷面膜");
  }
    
  @AfterReturning("sleeppoint()")
  public void afterSleep(){
    System.out.println("睡觉后要做美梦");
  }
Copy after login

Just write in the configuration file:

<!--扫描包 -->
   <context:component-scan base-package="com.tgb" annotation-config="true"/> 
   <!-- ASPECTJ注解 -->
   <aop:aspectj-autoproxy proxy-target-class="true" /> 
     
   <!-- 目标类 -->
   <bean id="lina" class="com.tgb.springaop.service.impl.ChenLliNa"/>
Copy after login

4. Injection form of Aspcet aspect
Personally feel that this is the simplest and most commonly used, and also the most flexible of. The configuration file is as follows:

<!-- 目标类 -->
  <bean id="lina" class="com.tgb.springaop.service.impl.ChenLliNa"/>
  <bean id ="sleepHelper" class="com.tgb.springaop.aspect.SleepHelper02"/>
    
  <aop:config>
    <aop:aspect ref="sleepHelper">
       <aop:before method="beforeSleep" pointcut="execution(* *.sleep(..))"/>
       <aop:after method="afterSleep" pointcut="execution(* *.sleep(..))"/>
    </aop:aspect>
  </aop:config>
Copy after login

The SleepHelper02 class mentioned in the configuration file is as follows:

/**
 * 通过注解的方式 添加增强
 */
  
public class SleepHelper02 {
  public void beforeSleep(){
    System.out.println("睡觉前要敷面膜");
  }
  public void afterSleep(){
    System.out.println("睡觉后要做美梦");
  }
}
Copy after login


Doesn’t it look very simple? Will everyone use spring aop? !

Regarding how to call, here are several test classes written. You can take a look, they are basically the same:

/**
 * 配置文件 spring_aop.xml 通过代理
 */
@Test
public void test(){
  ApplicationContext ct = new ClassPathXmlApplicationContext("spring_aop.xml");
    
  Sleepable sleeper =(Sleepable) ct.getBean("linaProxy");
    
  sleeper.sleep();
}
  
/**
 * 配置文件 spring_aop_01.xml  简答的java对象
 */
@Test
public void test01(){
  ApplicationContext ct = new ClassPathXmlApplicationContext("spring_aop_01.xml");
    
  Sleepable sleeper = (Sleepable)ct.getBean("lina");
    
  sleeper.sleep();
}
  
/**
 * 配置文件 spring_aop_03.xml 通过aspect注解
 */
@Test
public void test03(){
  ApplicationContext ct = new ClassPathXmlApplicationContext("spring_aop_03.xml");
    
    Sleepable sleeper = (Sleepable)ct.getBean("lina");
    
  sleeper.sleep();
}
/**
 * 配置文件 spring_aop_02.xml 通过apsect配置文件
 * @author 陈丽娜
 * @version 2015年5月31日上午10:09:37
 */
@Test
public void test02(){
  ApplicationContext ct = new ClassPathXmlApplicationContext("spring_aop_02.xml");
    
  Sleepable sleeper = (Sleepable)ct.getBean("lina");
    
  sleeper.sleep();
}
Copy after login


# #It can be seen from the test classes that no matter how aop is implemented, there is no difference in their use. The results of these test classes are the same:

Examples to explain AOP implementation in Javas Spring framework

For more examples to explain the AOP implementation in Java's Spring framework, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template