SPRINGBOOT注解AOP编程(20200720)

引入依赖包

<dependency>
    <groupId>
org.springframework.boot</groupId>
    <artifactId>
spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>
org.aspectj</groupId>
    <artifactId>
aspectjweaver</artifactId>
</dependency>

 

 

AOP注解说明

@Aspect    //表示一个切面

@Component  //注册为一个组件

public class AopTest {

 

@Pointcut("execution( public *

 org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(..))")

//定义切面切入点,这里表示ThreadPoolTaskExecutor类的execute方法作为切入点

public void pointCut(){//这里名字随便取,但是其他地方需要保持一致,

如@Before("pointCut()"),@After("pointCut()")等

    }

 

    @Before("pointCut()")//切入点之前执行

    public void testBefore(JoinPoint joinPoint) {//参数可以为空,不为空可以是JoinPoint

       System.out.println("pointCut():testBefore");

    }

 

    @After("pointCut()")//切入点之后执行

    public void testAfter() {

        System.out.println("pointCut():testAfter");

    }

 

    @AfterReturning("pointCut()")//切入点返回执行

    public void testAfterReturning() {

        System.out.println("pointCut():testAfterReturning");

    }

 

    @AfterThrowing("pointCut()")//切入点抛异常执行

    public void testAfterThrowing() {

        System.out.println("pointCut():testAfterThrowing");

    }

 

    @Around("pointCut()")//环绕切入点,注意这里参数是ProceedingJoinPoint

    public void deAround(ProceedingJoinPoint joinPoint) throws Throwable{

        // 获取目标方法的名称

        String methodName = joinPoint.getSignature().getName();

        System.out.println("methodName = " + methodName);

        Object[] args = joinPoint.getArgs();

        for (Object arg : args) {

            System.out.println(arg);

        }

        joinPoint.proceed();//执行实际切入点方法

    }

}

 

注意:

如果运行后没有执行切面内容,检查@ComponentScan(basePackages = {"com.fullsee.aop","com.fullsee.factory", "com.fullsee.start", "com.fullsee.start.runner"})中是否包含Aop切面配置所在目录,如果没有需要加上。满足以上条件之后,只要执行切入点所在方法就会自动执行切面中的方法。

切面直接作用于ThreadRunnaberun方法,可以用如下配置

@Pointcut("execution( public * java.util.concurrent.Executor.*(..)))")

 

 

示例

package com.fullsee.aop;

import
org.aspectj.lang.JoinPoint;
import
org.aspectj.lang.ProceedingJoinPoint;
import
org.aspectj.lang.annotation.*;
import
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import
org.springframework.stereotype.Component;

import
java.util.StringJoiner;
import
java.util.concurrent.BlockingQueue;

/**
 *
<li>文件名称: 题目名称</li>
 
* <li>文件描述: 题目名称 功能描述</li>
 
* <li>版权所有: 版权所有© 2005-2019</li>
 
* <li> : Fullsee</li>
 
* <li>内容摘要: </li>
 
* <li>其他说明:</li>
 
* <li>完成日期: 2020-07-20 9:40 </li>
 
* <li>修改记录: </li>
 
*
 * @author songyunbing
 * @version
产品版本
 */
@Aspect
@Component

public class AopTest {

   
@Pointcut("execution( public * org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(..))")
   
public void pointCut(){

    }

   
@Before("pointCut()")
   
public void testBefore(JoinPoint joinPoint) {
        System.
out.println("pointCut():testBefore start");
       
Object aThis = joinPoint.getThis();
        if
(aThis instanceof ThreadPoolTaskExecutor){
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) aThis
;
           
printThreadPoolInfo(executor);
       
}
        Object[] args = joinPoint.getArgs()
;
        for
(Object arg : args) {
            System.
out.println(arg);
            if
(arg instanceof Thread || arg instanceof Runnable){
                printThreadInfo(arg)
;
           
}
        }
        System.
out.println("pointCut():testBefore end");

   
}
   
private void printThreadPoolInfo(ThreadPoolTaskExecutor taskExecutor){
       
//活动线程数
       
int activeCount = taskExecutor.getActiveCount();
        int
poolSize = taskExecutor.getPoolSize();
        int
maxPoolSize = taskExecutor.getMaxPoolSize();
        int
corePoolSize = taskExecutor.getCorePoolSize();
        long
taskCount = taskExecutor.getThreadPoolExecutor().getTaskCount();

        long
completedTaskCount = taskExecutor.getThreadPoolExecutor().getCompletedTaskCount();
        int
largestPoolSize = taskExecutor.getThreadPoolExecutor().getLargestPoolSize();
        int
maximumPoolSize = taskExecutor.getThreadPoolExecutor().getMaximumPoolSize();

       
BlockingQueue<Runnable> queue = taskExecutor.getThreadPoolExecutor().getQueue();
       
//队列当前排队线程数
       
int queueSize = queue.size();
       
//剩余队列大小
       
int remainingCapacity = queue.remainingCapacity();



       
StringJoiner sj = new StringJoiner("\r\n","线程池详情:\r\n","\r\n=======================\r\n");
       
sj.add("线程池的基本大小【corePoolSize="+corePoolSize)
                .add(
"线程池中允许的最大线程数【maxPoolSize="+maxPoolSize)
                .add(
"线程池中当前线程的数量【poolSize="+poolSize)
                .add(
"任务计数【taskCount="+taskCount)
                .add(
"活动线程数【activeCount="+activeCount)
                .add(
"完成线程任务数【completedTaskCount="+completedTaskCount)
                .add(
"出现的最大线程个数【largestPoolSize="+largestPoolSize)
                .add(
"线程池中允许的最大线程数【maximumPoolSize="+maximumPoolSize)
                .add(
"剩余队列大小【remainingCapacity="+remainingCapacity)
                .add(
"队列当前排队线程数【queueSize="+queueSize);
       
System.out.println(sj.toString());
   
}
   
private void printThreadInfo(Object obj){

        Thread thread =
null;
        if
(obj instanceof Thread){
            thread = (Thread)obj
;
       
}else if(obj instanceof Runnable){
            thread =
new Thread((Runnable) obj);
       
}
       
if(thread != null) {
           
long id = thread.getId();
           
String name = thread.getName();
           
Thread.State state = thread.getState();
            int
priority = thread.getPriority();
            
ThreadGroup threadGroup = thread.getThreadGroup();
           
Class<? extends Thread> aClass = thread.getClass();
           
StringJoiner sj = new StringJoiner("\r\n", "线程详情:\r\n", "\r\n=======================\r\n");
           
sj.add("线程IDid=" + id)
                    .add(
"线程名称【name=" + name)
                    .add(
"线程状态【state=" + state.name())
                    .add(
"优先级【priority=" + priority)
                    .add(
"线程组【threadGroup=" + threadGroup.getName())
                    .add(
"线程类【Class=" + aClass);
           
System.out.println(sj.toString());
       
}
    }

   
private void printThreadInfo(Runnable runnable){

        Thread thread =
new Thread(runnable);
        long
id = thread.getId();
       
String name = thread.getClass().getName();
       
Thread.State state = thread.getState();
        int
priority = thread.getPriority();
       
ThreadGroup threadGroup = thread.getThreadGroup();
       
Class<? extends Thread> aClass = thread.getClass();
       
StringJoiner sj = new StringJoiner("\r\n","线程详情:\r\n","\r\n=======================\r\n");
       
sj.add("线程IDid="+id)
                .add(
"线程名称【name="+name)
                .add(
"线程状态【state="+state.name())
                .add(
"优先级【priority="+priority)
                .add(
"线程组【threadGroup="+threadGroup.getName())
                .add(
"线程类【Class="+aClass);
       
System.out.println(sj.toString());
   
}

   
@After("pointCut()")
   
public void testAfter() {
        System.
out.println("pointCut():testAfter");
   
}

   
@AfterReturning("pointCut()")
   
public void testAfterReturning() {
        System.
out.println("pointCut():testAfterReturning");
   
}

   
@AfterThrowing("pointCut()")
   
public void testAfterThrowing() {
        System.
out.println("pointCut():testAfterThrowing");
   
}

   
@Around("pointCut()")
   
public void deAround(ProceedingJoinPoint joinPoint) throws Throwable{
       
// 获取目标方法的名称
       
String methodName = joinPoint.getSignature().getName();
       
System.out.println("methodName = " + methodName);
       
Object[] args = joinPoint.getArgs();
        for
(Object arg : args) {
            System.
out.println(arg);
       
}
        joinPoint.proceed()
;
   
}
}

 

 

 

@EnableAsync
@SpringBootApplication
(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"com.fullsee.aop","com.fullsee.factory", "com.fullsee.start", "com.fullsee.start.runner"})
public class StartRunner {
   
public static void main(String[] args) {
        SpringApplication.run(StartRunner.
class);
   
}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值