Java Spring AOP的兩種配置方式

來源:互聯網
上載者:User

標籤:password   private   public   return   切入點   

第一種:註解配置AOP

java中註解配置AOP(使用 AspectJ 類庫實現的),大致分為三步:

1. 使用註解@Aspect來定義一個切面,在切面中定義切入點(@Pointcut),通知類型(@Before, @AfterReturning,@After,@AfterThrowing,@Around).
2. 開發需要被攔截的類。
3. 將切面配置到xml中,當然,我們也可以使用自動掃描Bean的方式。這樣的話,那就交由Spring AoP容器管理。

另外需要引用 aspectJ 的 jar 包: aspectjweaver.jar aspectjrt.jar

執行個體:

  1. User.java

  2. package com.bjsxt.model;


  3. public class User {

  4.     private String username;

  5.     private String password;

  6.     public String getUsername() {

  7.         return username;

  8.     }

  9.     public void setUsername(String username) {

  10.         this.username = username;

  11.     }

  12.     public String getPassword() {

  13.         return password;

  14.     }

  15.     public void setPassword(String password) {

  16.         this.password = password;

  17.     }

  18. }

  19. /**

  20. *介面類

  21. */

  22. package com.bjsxt.dao;

  23. import com.bjsxt.model.User;


  24. public interface UserDAO {

  25.     public void save(User user);

  26. }

複製代碼

實現介面:

  1. package com.bjsxt.dao.impl;


  2. import org.springframework.stereotype.Component;


  3. import com.bjsxt.dao.UserDAO;

  4. import com.bjsxt.model.User;


  5. @Component("u")

  6. public class UserDAOImpl implements UserDAO {


  7.     public void save(User user) {


  8.         System.out.println("user save11d!");

  9.         /*throw new RuntimeException("exception");*/ //拋異常

  10.     }


  11. }

複製代碼

操作類:

  1. package com.bjsxt.service;

  2. import javax.annotation.Resource;


  3. import org.springframework.beans.factory.annotation.Autowired;

  4. import org.springframework.beans.factory.annotation.Qualifier;

  5. import org.springframework.stereotype.Component;


  6. import com.bjsxt.dao.UserDAO;

  7. import com.bjsxt.model.User;


  8. @Component("userService")

  9. public class UserService {


  10.     private UserDAO userDAO;  


  11.     public void init() {

  12.         System.out.println("init");

  13.     }


  14.     public void add(User user) {

  15.         userDAO.save(user);

  16.     }

  17.     public UserDAO getUserDAO() {

  18.         return userDAO;

  19.     }


  20.     @Resource(name="u")

  21.     public void setUserDAO( UserDAO userDAO) {

  22.         this.userDAO = userDAO;

  23.     }


  24.     public void destroy() {

  25.         System.out.println("destroy");

  26.     }

  27. }

複製代碼

加入aop

  1. package com.bjsxt.aop;


  2. import org.aspectj.lang.annotation.After;

  3. import org.aspectj.lang.annotation.AfterReturning;

  4. import org.aspectj.lang.annotation.AfterThrowing;

  5. import org.aspectj.lang.annotation.Aspect;

  6. import org.aspectj.lang.annotation.Before;

  7. import org.aspectj.lang.annotation.Pointcut;

  8. import org.springframework.stereotype.Component;


  9. @Aspect

  10. @Component

  11. public class LogInterceptor {

  12.     @Pointcut("execution(public * com.bjsxt.service..*.add(..))")

  13.     public void myMethod(){};


  14.     /*@Before("execution(public void com.bjsxt.dao.impl.UserDAOImpl.save(com.bjsxt.model.User))")*/

  15.     @Before("myMethod()")

  16.     public void before() {

  17.         System.out.println("method staet");

  18.     } 

  19.     @After("myMethod()")

  20.     public void after() {

  21.         System.out.println("method after");

  22.     } 

  23.     @AfterReturning("execution(public * com.bjsxt.dao..*.*(..))")

  24.     public void AfterReturning() {

  25.         System.out.println("method AfterReturning");

  26.     } 

  27.     @AfterThrowing("execution(public * com.bjsxt.dao..*.*(..))")

  28.     public void AfterThrowing() {

  29.         System.out.println("method AfterThrowing");

  30.     } 

  31. }

複製代碼

設定檔

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4.        xmlns:context="http://www.springframework.org/schema/context"

  5.        xmlns:aop="http://www.springframework.org/schema/aop"

  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans


  7. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd



  8. http://www.springframework.org/schema/context



  9. http://www.springframework.org/schema/context/spring-context-2.5.xsd



  10. http://www.springframework.org/schema/aop



  11. http://www.springframework.org/schema/aop/spring-aop-3.1.xsd


  12.            "><!-- 要添加最後2行 -->


  13.     <context:annotation-config />

  14.     <context:component-scan base-package="com.bjsxt"/>  <!-- 自動掃描 -->

  15.     <aop:aspectj-autoproxy/>  <!-- 要添加本行 -->

  16. </beans>

複製代碼

測試類別:

  1. package com.bjsxt.service;

  2. import org.junit.Test;

  3. import org.springframework.context.ApplicationContext;

  4. import org.springframework.context.support.ClassPathXmlApplicationContext;


  5. import com.bjsxt.model.User;


  6. //Dependency Injection

  7. //Inverse of Control

  8. public class UserServiceTest {


  9.     @Test

  10.     public void testAdd() throws Exception {

  11.         ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");


  12.         UserService service = (UserService)ctx.getBean("userService");

  13.         System.out.println(service.getClass());

  14.         service.add(new User());

  15.         System.out.println("###");


  16.         ctx.destroy();


  17.     }


  18. }

複製代碼

結果:

  1. class com.bjsxt.service.UserService$EnhancerByCGLIB$7b201784

  2. method staet

  3. user save11d!

  4. method AfterReturning

  5. method after

  6. ###

複製代碼

注意:

  • @Aspect:意思是這個類為切面類

  • @Componet:因為作為切面類需要 Spring 管理起來,所以在初始化時就需要將這個類初始化加入 Spring 的管理;

  • @Befoe:切入點的邏輯(Advice)

  • execution…:切入點文法

第二種:xml配置aop

執行個體同上:只是設定檔不同

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4.        xmlns:context="http://www.springframework.org/schema/context"

  5.        xmlns:aop="http://www.springframework.org/schema/aop"

  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans


  7. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd



  8. http://www.springframework.org/schema/context



  9. http://www.springframework.org/schema/context/spring-context-2.5.xsd



  10. http://www.springframework.org/schema/aop



  11. http://www.springframework.org/schema/aop/spring-aop-3.1.xsd


  12.            "><!-- 要添加最後2行 -->


  13.     <context:annotation-config />

  14.     <context:component-scan base-package="com.bjsxt"/>

  15.     <bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>

  16.     <aop:config>

  17.         <aop:pointcut expression="execution(public * com.bjsxt.service..*.add(..))" 

  18.         id="servicePointcut"/>

  19.         <aop:aspect id="logAspect" ref="logInterceptor">

  20.             <aop:before method="before"  pointcut-ref="servicePointcut" />

  21.         </aop:aspect>


  22.     </aop:config>

  23. </beans>

複製代碼

下面的<beans>是Spring的配置標籤,beans裡面幾個重要的屬性:

xmlns:

是預設的xml文檔解析格式,即spring的beans。地址是http://www.springframework.org/schema/beans。

通過設定這個屬性,所有在beans裡面聲明的屬性,可以直接通過<>來使用,比如<bean>等等。

xmlns:xsi:

是xml需要遵守的規範,通過URL可以看到,是w3的統一規範,後面通過xsi:schemaLocation來定位所有的解析檔案。

xmlns:aop:

這個是重點,是我們這裡需要使用到的一些語義規範,與面向切面AOP相關。

xmlns:tx:

Spring中與事務相關的配置內容。

一個XML檔案,只能聲明一個預設的語義解析的規範。

例如上面的xml中就只有beans一個是預設的,其他的都需要通過特定的標籤來使用,比如aop,它自己有很多的屬性,如果要使用,前面就必須加上aop:xxx才可以。比如上面的aop:config。

類似的,如果預設的xmlns配置的是aop相關的語義解析規範,那麼在xml中就可以直接寫config這種標籤了。


Java Spring AOP的兩種配置方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.