springboot aop 方法执行前do something

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.big.data.crawler.leader.zk.ZKCrawlerLeaderService;

@Aspect
@Component
public class JudgeLeaderAspect {
	private static final Logger logger = LoggerFactory
			.getLogger(JudgeLeaderAspect.class);
	@Autowired
	private ZKCrawlerLeaderService zKCrawlerLeaderService;
	//拦截类StoreRelationService中所有已job结尾的方法
	@Pointcut("execution(public * com.big.data.crawler.scheduler.store.StoreRelationService.*Job(..))")
	public void isLeader(){}
	
	@Around("isLeader()")
        //@Before("isLeader()")	该注解不能阻止目标方法的执行
	public void doBefore(ProceedingJoinPoint joinPoint) throws Throwable{
		if(!zKCrawlerLeaderService.isLeader()) {
			logger.info("本节点不是主节点,放弃调度任务");
		}else {
			joinPoint.proceed();
		}
		
	}
}

1、跟springboot结合,在pom中引入依赖

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

        </dependency> 


2、定义一个切面类,加上注解

 
 
@Aspect
@Component
public class JudgeLeaderAspect {}

3、@Before注解只能在方法之前前做一些事,不能阻止方法的执行

       如果需要阻止方法的执行,请用@Around注解


猜你喜欢

转载自blog.csdn.net/a469517790/article/details/80347494