java框架--Spring XML AOP 配置基础(二)

 1. AOP的原理  点击查看

Spring有两大核心,IOC和AOP。IOC在java web项目中无时无刻不在使用。然而AOP用的比较少,的确也是一般的项目用的场所不多。事务控制基本都用,但却是Spring封装的不需要我们再去实现,但Spring的AOP远 不止这些,不能因为项目中没有使用,而不去学习及理解。我觉得这是作为一个java web软件开发人员必须具备的技能。业内很多将AOP应用在日志记录上,可惜我们项目没这么做,后面需要学习下。在这先把Spring    AOP的基本用法,在脑子里理一边,做一次积累。

2、概念术语  

  在开始之前,需要理解Spring aop 的一些基本的概念术语(总结的个人理解,并非Spring官方定义):

  切面(aspect):用来切插业务方法的类。

  连接点(joinpoint):是切面类和业务类的连接点,其实就是封装了业务方法的一些基本属性,作为通知的参数来解析。

  通知(advice):在切面类中,声明对业务方法做额外处理的方法。

  切入点(pointcut):业务类中指定的方法,作为切面切入的点。其实就是指定某个方法作为切面切的地方。

  目标对象(target object):被代理对象。

  AOP代理(aop proxy):代理对象。

  通知:

  前置通知(before advice):在切入点之前执行。

  后置通知(after returning advice):在切入点执行完成后,执行通知。

  环绕通知(around advice):包围切入点,调用方法前后完成自定义行为。

  异常通知(after throwing advice):在切入点抛出异常后,执行通知。

3、Spring AOP环境

  要在项目中使用Spring AOP 则需要在项目中导入除了spring jar包之外,还有aspectjweaver.jar,aopalliance.jar ,asm.jar 和cglib.jar 。

好了,前提工作准备完成,Spring 提供了很多的实现AOP的方式,在学习过程中,循序渐进。进行Spring 接口方式,schema配置方式和注解的三种方式进行学习。好了废话不多说了,开始spring aop学习之旅:

4、方式一:AOP接口

  利用Spring AOP接口实现AOP,主要是为了指定自定义通知来供spring AOP机制识别。主要接口:前置通知 MethodBeforeAdvice ,后置通知:AfterReturningAdvice,环绕通知:MethodInterceptor,异常通知:         ThrowsAdvice 。见例子代码:

package cn.sxt.log;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class AfterLog implements AfterReturningAdvice{
    /**
     * 目标方法执行后执行的通知
     * returnValue--返回值
     * method 被调用的方法对象
     * args 被调用的方法对象的参数
     * target 被调用的方法对象的目标对象
     * */
    @Override
    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被成功执行,返回值是:"+returnValue);
    }
}

AfterLog

package cn.sxt.log;

import java.lang.reflect.Method;

import org.springframework.aop.ThrowsAdvice;

public class ExceptionLog implements ThrowsAdvice {
    public void afterThrowing(Method method,Exception ex) throws Throwable {
    }

}

ExceptionLog

package cn.sxt.log;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class Log implements MethodBeforeAdvice{
    /**
     * @param method 被调用方法对象
     * @param args 被调用的方法的参数
     * @param target 被调用的方法的目标对象
     * */
    @Override
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被执行");
    }
}

Log

package cn.sxt.service;

public interface UserService {
    public void add();
    public String update(int a);
    public void delete();
    public void search();
}

UserService

package cn.sxt.service.impl;

import cn.sxt.service.UserService;

public class UserServiceImpl implements UserService {

    @Override
    public void add() {
        System.out.println("增加用户");
    }

    @Override
    public String update(int a) {
        System.out.println("修改用户");
        return "abc";
    }    

    @Override
    public void delete() {
        System.out.println("删除用户");
    }

    @Override
    public void search() {
        System.out.println("查询用户");
    }

}

UserServiceImpl

package cn.sxt.test;

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

import cn.sxt.service.UserService;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService)ac.getBean("userService");
        userService.update(2);
    }
}
/*cn.sxt.service.impl.UserServiceImpl的update方法被执行
    修改用户
cn.sxt.service.impl.UserServiceImpl的update被成功执行,返回值是:abc*/

Test

<?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:aop="http://www.springframework.org/schema/aop"
    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.xsd">
    <bean id="userService" class="cn.sxt.service.impl.UserServiceImpl"/>
    <bean id="log" class="cn.sxt.log.Log"/>
    <bean id="afterLog" class="cn.sxt.log.AfterLog"/>
    <aop:config>
        <aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

beans.xml

方式二:AOP接口

package cn.sxt.log;

public class Log {
    public void before(){
        System.out.println("-----方法执行前-----");
    }
    public void after(){
        System.out.println("-----方法执行后-----");
    }
}

Log

package cn.sxt.service;

public interface UserService {
    public void add();
    public int delete();
}

UserService

package cn.sxt.service.impl;

import cn.sxt.service.UserService;

public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("-------添加用户数据-------");
    }
    @Override
    public int delete() {
        System.out.println("-------删除用户数据-------");
        return 1;
    }
}

UserServiceImpl

package cn.sxt.test;

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

import cn.sxt.service.UserService;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService)ac.getBean("userService");
        userService.delete();
    }
}
/*-----方法执行前-----
-------删除用户数据-------
-----方法执行后-----
*/

Test

<?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:aop="http://www.springframework.org/schema/aop"
    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.xsd">
    <bean id="userService" class="cn.sxt.service.impl.UserServiceImpl"/>
    <bean id="log" class="cn.sxt.log.Log"/>
    <aop:config>
          <aop:aspect ref="log">
              <aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))" id="pointcut"/>
              <aop:before method="before" pointcut-ref="pointcut"/>
              <aop:after method="after" pointcut-ref="pointcut"/>
          </aop:aspect>
      </aop:config>
</beans>

beans.xml

方式三:AOP接口   (包名和类位置和二一样)

package cn.sxt.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Log {
    @Before("execution(* cn.sxt.service.impl.*.*(..))")
    public void before(){
        System.out.println("-----方法执行前-----");
    }
    @After("execution(* cn.sxt.service.impl.*.*(..))")
    public void after(){
        System.out.println("-----方法执行后-----");
    }
    @Around("execution(* cn.sxt.service.impl.*.*(..))")
    public Object aroud(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("环绕前");
        System.out.println("签名:"+jp.getSignature());
        //执行目标方法
         Object result = jp.proceed();
        System.out.println("环绕后");
        return result;
    }
}

Log

package cn.sxt.service;

public interface UserService {
    public void add();
    public int delete();
}

UserService

package cn.sxt.service.impl;

import cn.sxt.service.UserService;

public class UserServiceImpl implements UserService{
    @Override
    public void add() {
        System.out.println("-------添加用户数据-------");
    }
    public int add(int a,int c){
        return 1;
    }
    @Override
    public int delete() {
        System.out.println("-------删除用户数据-------");
        return 1;
    }
}

UserServiceImpl

package cn.sxt.test;

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

import cn.sxt.service.UserService;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService)ac.getBean("userService");
        userService.delete();
    }
}
/*环绕前
签名:int cn.sxt.service.UserService.delete()
-----方法执行前-----
-------删除用户数据-------
环绕后
-----方法执行后-----
*/

Test

<?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:aop="http://www.springframework.org/schema/aop"
    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.xsd">
    <bean id="userService" class="cn.sxt.service.impl.UserServiceImpl"/>
    <bean id="log" class="cn.sxt.log.Log"/>

    <aop:aspectj-autoproxy/>
</beans>

beans.xml

原文地址:https://www.cnblogs.com/ou-pc/p/8214846.html

时间: 2024-08-29 01:01:24

java框架--Spring XML AOP 配置基础(二)的相关文章

跟着刚哥学习Spring框架--通过XML方式配置Bean(三)

Spring配置Bean有两种形式(XML和注解) 今天我们学习通过XML方式配置Bean 1. Bean的配置方式 通过全类名(反射)的方式   √ id:标识容器中的bean.id唯一. √ class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参的构造器 2.依赖注入的方式 1)属性注入:通过setter方法注入Bean的属性值或依赖的对象 属性注入使用<Property>元素,使用name指定Bean的属性名称,使用value指定Bean的属

Java框架spring Boot学习笔记(十三):aop实例操作

使用aop需要在网上下载两个jar包: aopalliance.jar aspectjweaver.jar 为idea添加jar包,快捷键ctrl+shift+alt+s,打开添加jar包的对话框,将刚才下载好的jar添加进去 前置增强实例 编写TimeHandler.java 1 package com.example.spring; 2 3 public class TimeHandler { 4 public void beforTime() 5 { 6 System.out.printl

【常用配置】Spring框架web.xml通用配置

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="Web

java框架-----spring框架------在自己的项目中如何用maven管理spring相关jar包

1.文章内容概述: spring框架是支持maven的,因为spring框架的所有模块打包而成的jar包以及spring所依赖的其他jar包都被存放了一份在maven的中央仓库中,如果你的项目使用maven进行管理,那么你就可以在你的项目中通过maven来引入你的项目所依赖的spring相关的jar包或其他依赖库. 2.spring框架中maven相关的东西: 概述:使用maven管理spring相关的jar包,需要在pom.xml中配置groupId.artifactId之类的东西,只有在po

JAVA 框架 Spring Cache For Redis.

一.概述 缓存(Caching)可以存储经常会用到的信息,这样每次需要的时候,这些信息都是立即可用的. 常用的缓存数据库: Redis   使用内存存储(in-memory)的非关系数据库,字符串.列表.集合.散列表.有序集合,每种数据类型都有自己的专属命令.另外还有批量操作(bulk operation)和不完全(partial)的事务支持 .发布与订阅.主从复制(master/slave replication).持久化.脚本(存储过程,stored procedure). 效率比ehcac

Spring Java-based容器配置(二)

### 组装Java-based的配置 * 使用@Import注解 跟在Spring XML文件中使用`<import>`元素添加模块化的配置类似,@Import注解允许你加载其他配置类中的@Bean定义: ```java @Configuration public class ConfigA { @Bean public A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB

Java框架-Spring MVC理解001

Spring MVC理解 最近在读一本<看透springMVC>的书,从了解到了一些更加精细系统的知识,边读变分享吧. 1.servlet--Spring MVC的本质 2.Spring MVC其实是一个工具,具体的理解可以分为两步:第一步,了解这个工具是怎么创建出来的:第二步,了解这个工具是怎么用的. 3.前期使用准备:环境的搭建 ①创建WEB项目,导入jar包,Maven项目简单的加入springMVC和servlet的依赖就可以了. //Maven项目加入依赖 <dependenc

java框架spring的依赖注入初步理解

java框架的spring作为整个工程的统领者,可以有效地管理各层的对象,有效的协调运行,当系统西药重构时,可以极大地减少改写代码的量. 依赖注入和控制反转属于同一个概念,在java中当某个类(调用者)需要另一个类(被调用者)的协助时,在以往的程序设计理念中,通常由调用者类创建一个被调用者类的实例(new一个被调用者类),这种new一个对象的方法通常会在java空间中开创一个空间,对java项目整体运行效率会有一定的影响,而且是比较粗鲁的方式.但在spring框架里,创建调用类的工作不再由调用者

JAVA框架中XML文件

其实在JAVA开发中servlet配置,映射注入配置等等都可以用xml来配置 在此处的department是实体类的名字,而不是对应的数据库表的名字 数据库表的字段名=#{实体类属性名} 逆向工程生成的XML文件有查找更新等功能,但是当我们查找的时候需要返回一个类, 我们应该在开头写返回结果 resultMap id="自己起的名字" type="返回的结果类型,此处为Department实体类"  <id property="实体类主键名"