关闭 x
IT技术网
    技 采 号
    ITJS.cn - 技术改变世界
    • 实用工具
    • 菜鸟教程
    IT采购网 中国存储网 科技号 CIO智库

    IT技术网

    IT采购网
    • 首页
    • 行业资讯
    • 系统运维
      • 操作系统
        • Windows
        • Linux
        • Mac OS
      • 数据库
        • MySQL
        • Oracle
        • SQL Server
      • 网站建设
    • 人工智能
    • 半导体芯片
    • 笔记本电脑
    • 智能手机
    • 智能汽车
    • 编程语言
    IT技术网 - ITJS.CN
    首页 » JAVA »Java Spring AOP的两种配置方式

    Java Spring AOP的两种配置方式

    2015-05-05 00:00:00 出处:ImportNew
    分享

    第一种:注解配置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
    package com.bjsxt.model;
    
    public class User {
        private String username;
        private String password;
        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;
        }
    }
    /**
    *接口类
    */
    package com.bjsxt.dao;
    import com.bjsxt.model.User;
    
    public interface UserDAO {
        public void save(User user);
    }

    实现接口:

    package com.bjsxt.dao.impl;
    
    import org.springframework.stereotype.Component;
    
    import com.bjsxt.dao.UserDAO;
    import com.bjsxt.model.User;
    
    @Component("u")
    public class UserDAOImpl implements UserDAO {
    
        public void save(User user) {
    
            System.out.println("user save11d!");
            /*throw new RuntimeException("exception");*/ //抛异常
        }
    
    }

    操作类:

    package com.bjsxt.service;
    import javax.annotation.Resource;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Component;
    
    import com.bjsxt.dao.UserDAO;
    import com.bjsxt.model.User;
    
    @Component("userService")
    public class UserService {
    
        private UserDAO userDAO;  
    
        public void init() {
            System.out.println("init");
        }
    
        public void add(User user) {
            userDAO.save(user);
        }
        public UserDAO getUserDAO() {
            return userDAO;
        }
    
        @Resource(name="u")
        public void setUserDAO( UserDAO userDAO) {
            this.userDAO = userDAO;
        }
    
        public void destroy() {
            System.out.println("destroy");
        }
    }

    加入aop

    package com.bjsxt.aop;
    
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.AfterThrowing;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class LogInterceptor {
        @Pointcut("execution(public * com.bjsxt.service..*.add(..))")
        public void myMethod(){};
    
        /*@Before("execution(public void com.bjsxt.dao.impl.UserDAOImpl.save(com.bjsxt.model.User))")*/
        @Before("myMethod()")
        public void before() {
            System.out.println("method staet");
        } 
        @After("myMethod()")
        public void after() {
            System.out.println("method after");
        } 
        @AfterReturning("execution(public * com.bjsxt.dao..*.*(..))")
        public void AfterReturning() {
            System.out.println("method AfterReturning");
        } 
        @AfterThrowing("execution(public * com.bjsxt.dao..*.*(..))")
        public void AfterThrowing() {
            System.out.println("method AfterThrowing");
        } 
    }

    配置文件

    < xml version="1.0" encoding="UTF-8" >
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    
    
    http://www.springframework.org/schema/context
    
    
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    
    
    http://www.springframework.org/schema/aop
    
    
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    
               "><!-- 要添加最后2行 -->
    
        <context:annotation-config />
        <context:component-scan base-package="com.bjsxt"/>  <!-- 自动扫描 -->
        <aop:aspectj-autoproxy/>  <!-- 要添加本行 -->
    </beans>

    测试类:

    package com.bjsxt.service;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.bjsxt.model.User;
    
    //Dependency Injection
    //Inverse of Control
    public class UserServiceTest {
    
        @Test
        public void testAdd() throws Exception {
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            UserService service = (UserService)ctx.getBean("userService");
            System.out.println(service.getClass());
            service.add(new User());
            System.out.println("###");
    
            ctx.destroy();
    
        }
    
    }

    结果:

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

    注意:

    @Aspect:意思是这个类为切面类 @Componet:因为作为切面类需要 Spring 管理起来,所以在初始化时就需要将这个类初始化加入 Spring 的管理; @Befoe:切入点的逻辑(Advice) execution…:切入点语法

    第二种:xml配置aop

    实例同上:只是配置文件不同

    < xml version="1.0" encoding="UTF-8" >
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    
    
    http://www.springframework.org/schema/context
    
    
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    
    
    http://www.springframework.org/schema/aop
    
    
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    
               "><!-- 要添加最后2行 -->
    
        <context:annotation-config />
        <context:component-scan base-package="com.bjsxt"/>
        <bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
        <aop:config>
            <aop:pointcut expression="execution(public * com.bjsxt.service..*.add(..))" 
            id="servicePointcut"/>
            <aop:aspect id="logAspect" ref="logInterceptor">
                <aop:before method="before"  pointcut-ref="servicePointcut" />
            </aop:aspect>
    
        </aop:config>
    </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这种标签了。

    上一篇返回首页 下一篇

    声明: 此文观点不代表本站立场;转载务必保留本文链接;版权疑问请联系我们。

    别人在看

    Edge浏览器百度被劫持/篡改怎么办,地址后边跟着尾巴#tn=68018901_7_oem_dg

    Google Chrome 在 iPhone 上新增了 Safari 数据导入选项

    Windows 11专业版 KMS工具激活产品密钥的方法

    DEDECMS安全策略官方出品

    Microsoft Text Input Application 可以关闭吗?

    新版本QQ如何关闭自带的浏览器?

    C++编程语言中continue的用法和功能,附举例示范代码

    c++ map 的数据结构、基本操作以及其在实际应用中的使用。

    C语言如何避免内存泄漏、缓冲区溢出、空指针解引用等常见的安全问题

    C语言中的break语句详解

    IT头条

    马斯克2026最新采访总结:2040年,全球机器人数量将突破100亿台

    23:52

    专家解读|规范人工智能前沿业态健康发展的新探索:解读《人工智能拟人化互动服务管理暂行办法》

    00:54

    用至强 6高存力搞定MoE卸载!

    17:53

    美国将允许英伟达向中国“经批准的客户”出售H200 GPU

    02:08

    苹果与微信就15%手续费达成一致?腾讯未置可否

    22:00

    技术热点

    PHP 和 Node.js 的10项对比挑战

    Javascript闭包深入解析及实现方法

    windows 7、windows 8.1手动增加右键菜单功能技巧

    MYSQL出错代码大汇总

    windows 7假死机怎么办 windows 7系统假死机的原因以及解决方法

    Ubuntu(Linux)下配置IP地址的方法

      友情链接:
    • IT采购网
    • 科技号
    • 中国存储网
    • 存储网
    • 半导体联盟
    • 医疗软件网
    • 软件中国
    • ITbrand
    • 采购中国
    • CIO智库
    • 考研题库
    • 法务网
    • AI工具网
    • 电子芯片网
    • 安全库
    • 隐私保护
    • 版权申明
    • 联系我们
    IT技术网 版权所有 © 2020-2025,京ICP备14047533号-20,Power by OK设计网

    在上方输入关键词后,回车键 开始搜索。Esc键 取消该搜索窗口。