java框架篇---spring aop两种配置方式

简介:




java框架篇---spring aop两种配置方式


第一种:注解配置AOP

注解配置AOP(使用 AspectJ 类库实现的),大致分为三步:
1. 使用注解@Aspect来定义一个切面,在切面中定义切入点(@Pointcut),通知类型(@Before, @AfterReturning,@After,@AfterThrowing,@Around).
2. 开发需要被拦截的类。
3. 将切面配置到xml中,当然,我们也可以使用自动扫描Bean的方式。这样的话,那就交由Spring AoP容器管理。

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

实例:

User.java


 
 
  1. package com.bjsxt.model; 
  2.  
  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. }

 
 
  1. /** 
  2. *接口类 
  3. */ 
  4. package com.bjsxt.dao; 
  5. import com.bjsxt.model.User; 
  6.  
  7.  
  8. public interface UserDAO { 
  9.     public void save(User user); 

实现接口:


 
 
  1. package com.bjsxt.dao.impl; 
  2.  
  3. import org.springframework.stereotype.Component; 
  4.  
  5. import com.bjsxt.dao.UserDAO; 
  6. import com.bjsxt.model.User; 
  7.  
  8. @Component("u") 
  9. public class UserDAOImpl implements UserDAO { 
  10.  
  11.     public void save(User user) { 
  12.          
  13.         System.out.println("user save11d!"); 
  14.         /*throw new RuntimeException("exception");*/ //抛异常 
  15.     } 
  16.  

操作类:


 
 
  1. package com.bjsxt.service; 
  2. import javax.annotation.Resource; 
  3.  
  4. import org.springframework.beans.factory.annotation.Autowired; 
  5. import org.springframework.beans.factory.annotation.Qualifier; 
  6. import org.springframework.stereotype.Component; 
  7.  
  8. import com.bjsxt.dao.UserDAO; 
  9. import com.bjsxt.model.User; 
  10.  
  11.  
  12. @Component("userService") 
  13. public class UserService { 
  14.      
  15.     private UserDAO userDAO;   
  16.      
  17.     public void init() { 
  18.         System.out.println("init"); 
  19.     } 
  20.      
  21.     public void add(User user) { 
  22.         userDAO.save(user); 
  23.     } 
  24.     public UserDAO getUserDAO() { 
  25.         return userDAO; 
  26.     } 
  27.      
  28.     @Resource(name="u") 
  29.     public void setUserDAO( UserDAO userDAO) { 
  30.         this.userDAO = userDAO; 
  31.     } 
  32.     
  33.     public void destroy() { 
  34.         System.out.println("destroy"); 
  35.     } 

加入aop


 
 
  1. package com.bjsxt.aop; 
  2.  
  3. import org.aspectj.lang.annotation.After; 
  4. import org.aspectj.lang.annotation.AfterReturning; 
  5. import org.aspectj.lang.annotation.AfterThrowing; 
  6. import org.aspectj.lang.annotation.Aspect; 
  7. import org.aspectj.lang.annotation.Before; 
  8. import org.aspectj.lang.annotation.Pointcut; 
  9. import org.springframework.stereotype.Component; 
  10.  
  11. @Aspect 
  12. @Component 
  13. public class LogInterceptor { 
  14.     @Pointcut("execution(public * com.bjsxt.service..*.add(..))") 
  15.     public void myMethod(){}; 
  16.      
  17.     /*@Before("execution(public void com.bjsxt.dao.impl.UserDAOImpl.save(com.bjsxt.model.User))")*/ 
  18.     @Before("myMethod()") 
  19.     public void before() { 
  20.         System.out.println("method staet"); 
  21.     }  
  22.     @After("myMethod()") 
  23.     public void after() { 
  24.         System.out.println("method after"); 
  25.     }  
  26.     @AfterReturning("execution(public * com.bjsxt.dao..*.*(..))") 
  27.     public void AfterReturning() { 
  28.         System.out.println("method AfterReturning"); 
  29.     }  
  30.     @AfterThrowing("execution(public * com.bjsxt.dao..*.*(..))") 
  31.     public void AfterThrowing() { 
  32.         System.out.println("method AfterThrowing"); 
  33.     }  

配置文件


 
 
  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.             
  14.     <context:annotation-config /> 
  15.     <context:component-scan base-package="com.bjsxt"/>  <!-- 自动扫描 --> 
  16.     <aop:aspectj-autoproxy/>  <!-- 要添加本行 --> 
  17. </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.  
  6. import com.bjsxt.model.User; 
  7.  
  8. //Dependency Injection 
  9. //Inverse of Control 
  10. public class UserServiceTest { 
  11.  
  12.     @Test 
  13.     public void testAdd() throws Exception { 
  14.         ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 
  15.          
  16.          
  17.         UserService service = (UserService)ctx.getBean("userService"); 
  18.         System.out.println(service.getClass()); 
  19.         service.add(new User()); 
  20.         System.out.println("###"); 
  21.          
  22.         ctx.destroy(); 
  23.          
  24.     } 
  25.  

结果:

class com.bjsxt.service.UserService$$EnhancerByCGLIB$$7b201784
method staet
user save11d!
method AfterReturning
method after
###

注意:

@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.             
  14.     <context:annotation-config /> 
  15.     <context:component-scan base-package="com.bjsxt"/> 
  16.     <bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean> 
  17.     <aop:config> 
  18.         <aop:pointcut expression="execution(public * com.bjsxt.service..*.add(..))"  
  19.         id="servicePointcut"/> 
  20.         <aop:aspect id="logAspect" ref="logInterceptor"> 
  21.             <aop:before method="before"  pointcut-ref="servicePointcut" /> 
  22.         </aop:aspect> 
  23.          
  24.     </aop:config> 
  25. </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这种标签了。


作者:返回主页 偶my耶

来源:51CTO

相关文章
|
3月前
|
安全 Java 应用服务中间件
Spring Boot + Java 21:内存减少 60%,启动速度提高 30% — 零代码
通过调整三个JVM和Spring Boot配置开关,无需重写代码即可显著优化Java应用性能:内存减少60%,启动速度提升30%。适用于所有在JVM上运行API的生产团队,低成本实现高效能。
388 3
|
3月前
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
312 2
|
2月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
3月前
|
人工智能 Java API
构建基于Java的AI智能体:使用LangChain4j与Spring AI实现RAG应用
当大模型需要处理私有、实时的数据时,检索增强生成(RAG)技术成为了核心解决方案。本文深入探讨如何在Java生态中构建具备RAG能力的AI智能体。我们将介绍新兴的Spring AI项目与成熟的LangChain4j框架,详细演示如何从零开始构建一个能够查询私有知识库的智能问答系统。内容涵盖文档加载与分块、向量数据库集成、语义检索以及与大模型的最终合成,并提供完整的代码实现,为Java开发者开启构建复杂AI智能体的大门。
1907 58
|
2月前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
2月前
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
151 8
|
3月前
|
监控 Java 数据库
从零学 Dropwizard:手把手搭轻量 Java 微服务,告别 Spring 臃肿
Dropwizard 整合 Jetty、Jersey 等成熟组件,开箱即用,无需复杂配置。轻量高效,启动快,资源占用少,内置监控、健康检查与安全防护,搭配 Docker 部署便捷,是构建生产级 Java 微服务的极简利器。
370 3
|
3月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
647 5
|
3月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
471 0
|
2月前
|
监控 Java Spring
AOP 切面编程
AOP(面向切面编程)通过动态代理在不修改源码的前提下,对方法进行增强。核心概念包括连接点、通知、切入点、切面和目标对象。常用于日志记录、权限校验、性能监控等场景,结合Spring AOP与@Aspect、@Pointcut等注解,实现灵活的横切逻辑管理。
453 6
AOP 切面编程