AOP(面向切面编程)基于注解方式配置

 不会注解的小伙伴看这里哦:Spring常用注解!!!-CSDN博客

pom.xml

 
        
            org.springframework
            spring-context
            6.0.12
        
        
            org.springframework
            spring-aspects
            5.1.8.RELEASE
        
        
            org.slf4j
            slf4j-log4j12
            1.7.19
        
    

UserDaoImpl:

package com.by.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {

    @Override
    public void addUser(){
        System.out.println("insert into tb_user......");
    }
}

UserServiceImpl:

package com.by.service;

import com.by.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public void addUser(){
        userDao.addUser();
        //System.out.println(8/0);
    }
}

MyLogActive:(增强类)

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 

Project: Spring - MyLogAdvice

*

Powered by scl On 2024-01-05 15:04:11

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ @Component @Aspect public class MyLogAdvice { @Before("execution(* com.by.service.*.*(..))") public void before() { System.out.println("前置通知、。、"); } @After("execution(* com.by.service.*.*(..))") public void after() { System.out.println("最终通知、、、"); } @AfterReturning("execution(* com.by.service.*.*(..))") public void afterReturn(){ System.out.println("后置通知"); } @AfterThrowing("execution(* com.by.service.*.*(..))") public void afterThrowing(){ System.out.println("异常通知"); } @Around("execution(* com.by.service.*.*(..))") public void around(ProceedingJoinPoint joinPoint) { try { System.out.println("前环绕通知。。。"); joinPoint.proceed(); System.out.println("后环绕通知。。。"); } catch (Throwable e) { throw new RuntimeException(e); } } }

applicationContext.xml:



    
    

    
    

测试:

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.web;

import com.by.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 

Project: Spring - Client

*

Powered by scl On 2024-01-05 15:01:34

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class Client { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = applicationContext.getBean("userServiceImpl", UserService.class); System.out.println(userService); userService.addUser(); } }

结果展示:

AOP(面向切面编程)基于注解方式配置_第1张图片

你可能感兴趣的:(java,spring,开发语言)