首页 > 其他分享 >spring aop

spring aop

时间:2023-05-29 12:32:54浏览次数:37  
标签:spring jaeson aop springstudy import com AopService


<?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:security="http://www.springframework.org/schema/security"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
		http://www.springframework.org/schema/cache 
		http://www.springframework.org/schema/cache/spring-cache.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/security 
		http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" >

	
	<!-- 启用组件注解扫描 -->
	<context:component-scan base-package="com.jaeson.springstudy.aop" />
	
	<!-- 启用AOP注解扫描,@Aspect/@Pointcut/@Before/@After/@Around/@AfterReturning/@AfterThrowing -->
	<aop:aspectj-autoproxy expose-proxy="true"/>

</beans>


 

package com.jaeson.springstudy.aop;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jaeson.hibernatestudy.bean.User;
import com.jaeson.springstudy.aop.AopService;

public class TestAop {

	private ClassPathXmlApplicationContext context;
	
	@Before
	public void before() {
		context = new ClassPathXmlApplicationContext(new String[] {"testAOP.xml"});
	}
	
	@After
	public void after() {
		context.close();
	}
	
	@Test
	public void testMethodAop() {
		
		AopService service = context.getBean("aopService", AopService.class);
		System.out.println("====================================");
		service.get(100086L);
		System.out.println("====================================");
		service.save(new User());
		System.out.println("====================================");
		service.selfInvoke();
		System.out.println("====================================");
		service.selfInvoke(new User());
		System.out.println("====================================");
		service.selfInvocation();
		System.out.println("====================================");
		try {
			service.delete(95977L);
		} catch (RuntimeException ex) {
			System.out.println(ex.getMessage());
		}
		System.out.println("====================================");
		
	}
}

 

package com.jaeson.springstudy.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AopExample {
	
	private static final Logger logger = LoggerFactory.getLogger(AopExample.class);

	@Pointcut("execution(* com.jaeson..dao..*.*(..))")
    public void dataAccessOperation() {}
	
    @Pointcut("execution(* com.jaeson..service..*.*(..))")
    public void businessService() {}
    
    @Pointcut("execution(* com.jaeson.springstudy.aop.*Service.*(..)))")
    public void aspect() {}

    /*
	 * 配置前置通知,使用在方法businessService()上注册的切入点
	 * 同时接受JoinPoint切入点对象,可以没有该参数
	 */
	@Before("businessService()")
	public void before(JoinPoint joinPoint) {
		
		logger.info("before {}", joinPoint);
	}

	//配置后置通知,使用在方法businessService()上注册的切入点
	@After("businessService()")
	public void after(JoinPoint joinPoint) {

			logger.info("after {}", joinPoint);
	}

	//配置环绕通知,使用在方法dataAccessOperation()上注册的切入点
	//@Around的返回类型必须为Object,否则在织入非void返回类型的切入点时会抛出异常:
	//Null return value from advice does not match primitive return type for:
	@Around("dataAccessOperation()")
	public Object around(JoinPoint joinPoint) throws Throwable {
		
		Object result = null;
		long start = System.currentTimeMillis();
		
		logger.info("begin around {} !", joinPoint);
		result = ((ProceedingJoinPoint) joinPoint).proceed();
		long end = System.currentTimeMillis();
		logger.info("end around {} Use time : {} ms!", joinPoint, (end - start));
		
		return result;
	}

	//配置后置返回通知,使用在方法businessService()上注册的切入点
	@AfterReturning("businessService()")
	public void afterReturn(JoinPoint joinPoint) {

		logger.info("afterReturn {}", joinPoint);
	}

	//配置抛出异常后通知,使用在方法businessService()上注册的切入点
	@AfterThrowing(pointcut="businessService()", throwing="ex")
	public void afterThrow(JoinPoint joinPoint, RuntimeException ex) {
		
		logger.info("afterThrow {} with exception : {}", joinPoint, ex.getMessage());
	}
	
	//配置前置通知,拦截返回值类型为com.jaeson.hibernatestudy.bean.User的方法
	@Before("execution(com.jaeson.hibernatestudy.bean.User com.jaeson.springstudy.aop.*Service.*(..))")
	public void beforeReturnUser(JoinPoint joinPoint) {

		logger.info("beforeReturnUser {}", joinPoint);
	}

	//配置前置通知,拦截参数类型为com.jaeson.hibernatestudy.bean.User的方法
	@Before("execution(* com.jaeson.springstudy.aop.*Service.*(com.jaeson.hibernatestudy.bean.User))")
	public void beforeArgUser(JoinPoint joinPoint) {

		logger.info("beforeArgUser {}", joinPoint);
	}

	//配置前置通知,拦截含有long类型参数的方法,并将参数值注入到当前方法的形参id中
	@Before("aspect() && args(id)")
	public void beforeArgId(JoinPoint joinPoint, long id) {

		logger.info("beforeArgId {} ({})", joinPoint, id);
	}
}

 

package com.jaeson.springstudy.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.aop.framework.AopContext;

import com.jaeson.hibernatestudy.bean.User;

@Service
public class AopService {
	
	private static final Logger logger = LoggerFactory.getLogger(AopService.class);
	
	//自调用无法触发aop的解决办法
	//开启暴露Aop代理到ThreadLocal支持
	//<aop:aspectj-autoproxy expose-proxy="true"/><!—注解风格支持--> 
	//<aop:config expose-proxy="true"><!—xml风格支持-->   
	public void selfInvocation() {
		logger.info("AopService.selfInvocation() method . . .");
		((AopService)AopContext.currentProxy()).get(0L);
	}
	
	
	//非aop方法的自调用不会触发this方法的aop
	public void selfInvoke() {
		logger.info("AopService.selfInvoke() method . . .");
		this.get(0L);
	}
	//aop方法的自调用不会触发this方法的aop
	public void selfInvoke(User user) {
		logger.info("AopService.selfInvoke(User) method . . .");
		this.save(user);
	}
	
	
	public User get(long id) {

		logger.info("AopService.get(Long) method . . .");
		return new User();
	}

	public void save(User user) {
		
		logger.info("AopService.save(User) method . . .");
	}

	public void delete(long id) throws RuntimeException {

		logger.info("AopService.delete(Long) method . . .");
		throw new UnsupportedOperationException("AopService.delete(Long) throw UnsupportedOperationException");
}

}

 

 

[INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeArgId(AopExample.java:97) beforeArgId execution(User com.jaeson.springstudy.aop.AopService.get(long)) (100086) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeReturnUser(AopExample.java:83) beforeReturnUser execution(User com.jaeson.springstudy.aop.AopService.get(long)) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.get(AopService.java:39) AopService.get(Long) method . . . 
    ====================================
[INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeArgUser(AopExample.java:90) beforeArgUser execution(void com.jaeson.springstudy.aop.AopService.save(User)) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.save(AopService.java:45) AopService.save(User) method . . . 
    ====================================
[INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.selfInvoke(AopService.java:27) AopService.selfInvoke() method . . . 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.get(AopService.java:39) AopService.get(Long) method . . . 
    ====================================
[INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeArgUser(AopExample.java:90) beforeArgUser execution(void com.jaeson.springstudy.aop.AopService.selfInvoke(User)) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.selfInvoke(AopService.java:32) AopService.selfInvoke(User) method . . . 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.save(AopService.java:45) AopService.save(User) method . . . 
   ====================================
[INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.selfInvocation(AopService.java:20) AopService.selfInvocation() method . . . 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeArgId(AopExample.java:97) beforeArgId execution(User com.jaeson.springstudy.aop.AopService.get(long)) (0) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeReturnUser(AopExample.java:83) beforeReturnUser execution(User com.jaeson.springstudy.aop.AopService.get(long)) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.get(AopService.java:39) AopService.get(Long) method . . . 
    ====================================
[INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopExample.beforeArgId(AopExample.java:97) beforeArgId execution(void com.jaeson.springstudy.aop.AopService.delete(long)) (95977) 
    [INFO][2016-10-07 15:29:16] com.jaeson.springstudy.aop.AopService.delete(AopService.java:50) AopService.delete(Long) method . . . 
    AopService.delete(Long) throw UnsupportedOperationException

 

 

标签:spring,jaeson,aop,springstudy,import,com,AopService
From: https://blog.51cto.com/u_16131764/6370081

相关文章

  • Spring cloud 微服务架构之Ribbon/Fegin连接超时ReadTimeout问题
    问题描述:近期用Springcloud开发微服务架构时候,在服务与服务之间调用调试代码时候,出现链接超时。错误信息:ReadtimedoutexecutingGEThttp://service-batch/batchmanagement/datatransfer/querybyplanid?planid=PL00000102。发生原因:用IDE开发Debug模式调试代码时候,在处理该服......
  • Spring事务失效的场景
    (1)方法没有用public修饰会导致事务失效。解决方法:在方法上使用public修饰。(2)使用try-catch捕获异常没有抛出异常,而是由方法自己处理会导致事务失效。解决方法:处理了异常记得抛出。(3)方法抛出检查异常会导致事务失效,报错也会导致事务失效。解决方法:在@transactional注解上配置ro......
  • 对SpringIOC和SpringAOP的理解
    SpringIOC和SpringAOP是Spring的两个核心组件。SpringIOC:SpringIOC是一个管理bean的容器,能够帮我们管理bean的整个生命周期,在没有SpringIOC的时候,我们需要自己手动的管理bean以及bean的依赖关系,这样会增加耦合,而有了SpringIOC,它能帮我们管理bean以及bean的依赖关系,使得代码解耦。......
  • Spring中的单例bean是线程安全的吗?
    Spring并没有对单例bean作线程安全的处理,在并发条件下Spring的bean是否是线程安全的有如下两种情况:(1)无状态的bean:没有数据存储能力,例如service类和dao类都是无状态的bean,所以是线程安全的。(2)有状态的bean:有数据存储能力,在并发环境下会发生线程安全问题,需要自行保证线程安全问题,......
  • spring boot 限制初始值大小及参数中文详解
    要加“m”说明是MB,否则就是KB了.-Xms:初始值-Xmx:最大值 -Xmn:最小值java-Xms10m-Xmx80m-jarmod.jar & 时区设置 java-jar-Duser.timezone=GMT+08mod.jar& #----------------------------------------  #核心属性  #----------------------------------------   #BANN......
  • SpringBoot如何整合定时任务调度
    所有的系统开发里面定时调度绝对是一个核心的话题,对于定时调用的实现在实际开发之中可以使用:TimerTask,Quartz,SpringTask配置,实际上这里面最简单的配置就是Spring自己所提供的Task处理。如果要想实现定时调度,只需要配置一个定时调度的组件类即可:1.packagecom.gwolf.task;2.3.......
  • Spring Boot 自动配置一篇概览
    一、什么是自动配置bean自动配置类通过添加@AutoConfiguration注解实现。因为@AutoConfiguration注解本身是以@Configuration注解的,所以自动配置类可以算是一个标准的基于@Configuration注解的类。@Conditional注解可以用于声明自动配置启用条件,通常,我们可以使用@C......
  • Spring5_1
    1、Spring是什么Spring是分层的JavaSE/EE应用full-stack轻量级开源框架,以IoC(InverseOfControl:反转控制)和AOP(AspectOrientedProgramming:面向切面编程)为内核,提供了展现层SpringMVC和持久层SpringJDBC以及业务层事务管理等众多的企业级应用技术,还能整合开源世......
  • Spring Data JPA 入门
    注解说明@Entity(name="")类注解,用来注解该类是一个实体类并用来和数据库中的表建立关联关系。其中name表示该表的名称@Table(name="")类注解,跟@Entity(name="")作用一致@Id属性注解,该注解表明该属性字段是一个主键,该属性必须具备,不可缺少@GeneratedValue(strategy=......
  • SpringCloudAlibaba整合分布式事务Seata
    目录1整合分布式事务Seata1.1环境搭建1.1.1Nacos搭建1.1.2Seata搭建1.2项目搭建1.2.1项目示意1.2.2pom.xml1.2.2.1alibaba-demo模块1.2.2.2call模块1.2.2.3order模块1.2.2.4common模块1.2.3配置文件1.2.3.1order模块1.2.3.2call模块1.2.4OpenFeign调用1.2.5order......