spring中基于注解的各种通知

导包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

接口类

public interface IAccountService {
    void saveAccount();
    void updateAccount(int i);
    int deleteAccount();
}

接口实现类,接口实现类上标记Service注解这样就作为bean加载到容器中

@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    public void saveAccount() {
        System.out.println("保存账户");
    }

    public void updateAccount(int i) {
        System.out.println("修改账户:"+i);
    }

    public int deleteAccount() {
        System.out.println("删除账户");
        return 0;
    }
}

通知工具类

@Component("logger")  //因为不属于服务层使用Component注解可以加载到容器中
@Aspect  //标注当前类是一个切面类
public class Logger {
    //配置切入点
    @Pointcut("execution(* *..*.*(int))")
    private void pt1(){}

    @Before("pt1()")
    public void beforePrintLog(){
        System.out.println("前置通知...");
    }
    @After("pt1()")
    public void afterPrintLog(){
        System.out.println("后置通知...");
    }
    @AfterReturning("pt1()")
    public void rturnPrintLog(){
        System.out.println("返回通知...");
    }
    @AfterThrowing("pt1()")
    public void exceptionPrintLog(){
        System.out.println("异常通知...");
    }

    @Around("pt1()")
    public Object arountPrintLog(ProceedingJoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        try {
            System.out.println("环绕通知中的前置通知...");
            Object proceed = joinPoint.proceed(args);
            System.out.println("环绕通知中的后置通知...");
            return proceed;
        } catch (Throwable throwable) {
            System.out.println("环绕通知中的异常通知...");
            throw  new RuntimeException(throwable);
        }
        finally {
            System.out.println("环绕通知中的最终通知...");
        }
    }
}

配置类

@Configuration  //标注这是一个配置类
@ComponentScan(basePackages = "com.itheima")  //标注扫描包范围
@EnableAspectJAutoProxy   //标注可以使用AOP通知
public class SpringConfig {
}

测试类,放到单元测试中测试时需要导包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>

并添加相关的注解RunWith和ContextConfiguration

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(classes = SpringConfig.class)  //标记要使用的配置类
public class AccountTest {

    @Autowired
    IAccountService accountService;
    @Test
    public void test(){
        accountService.updateAccount(1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值