Spring AOP 第一个简单示例

build.gradle

dependencies {
    compile group: 'org.springframework', name: 'spring-aop', version: '5.2.1.RELEASE'
    compile 'org.springframework:spring-context:5.2.1.RELEASE'
    compile 'org.springframework:spring-core:5.2.1.RELEASE'
    compile 'org.aspectj:aspectjrt:1.8.9'
    compile 'org.aspectj:aspectjweaver:1.8.9'
}

java代码

@Aspect
@Component
public class LoginLogService {
     
    /**
     * 切入带你描述, 通过表达式来描述需要切入的点
     */
    @Pointcut("execution(* lab.anoper.aop.service.LoginServiceImpl.*(..))")
    private void loginPointcut() {
      }

    /**
     * Before advice 前置通知
     * @param joinPoint 连接点
     */
    @Before("loginPointcut()")
    public void beforeInvoke(JoinPoint joinPoint) {
     
        System.out.println("before invoke. joinPoint: " + joinPoint);
    }
}

@Service
public class LoginServiceImpl{
     
    public void login() {
     
        System.out.println("user login...");
    }

    public void logout() {
     
        System.out.println("user logout...");
    }
}

@Configuration
@EnableAspectJAutoProxy
public class JavaConfig {
     

}

public class LoginAspectDemo {
     
    public static void main(String[] args) {
     
        String scanPackage = "lab.anoper.aop";
        ApplicationContext context = new AnnotationConfigApplicationContext(scanPackage);
        LoginServiceImpl service = context.getBean(LoginServiceImpl.class);
        service.login();
        service.logout();
    }
}

你可能感兴趣的:(Spring,AOP)