Spring:纯注解AOP编程

告知Spring是基于注解的AOP编程

这里纯注解,不用在配置文件中写<aop:..>了

 改换为注解@EnableAspectjAutoproxy,在配置Bean中写,配置Bean就相当于配置文件

 UserService:

package com.baizhiedu.aop;

public interface UserService {
    public void register();

    public void login();
}

UserServiceImpl:

package com.baizhiedu.aop;

import org.springframework.stereotype.Service;

@Service //注解创建Service对象
public class UserServiceImpl implements UserService {
    @Override
    public void register() {
        System.out.println("UserServiceImpl.register");
    }

    @Override
    public void login() {
        System.out.println("UserServiceImpl.login");
    }
}

MyApsect:

package com.baizhiedu.aop;

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.springframework.stereotype.Component;

@Aspect //注解创建切面类
@Component //注解创建对象
public class MyApsect {
    //切入点
    @Pointcut("execution(* com.baizhiedu.aop..*.*(..))")
    public void pointCut(){}

    @Around("pointCut()")
    public Object arround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("-------Log--------");
        Object proceed=joinPoint.proceed();//原始方法执行

        return proceed;
    }
}

AppConfig:

package com.baizhiedu.aop;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackages = "com.baizhiedu.aop") //注解扫描aop包
@EnableAspectJAutoProxy //配置文件中
public class AppConfig {
}

package com.baizhiedu.aop;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan(basePackages = "com.baizhiedu.aop") //注解扫描aop包
@EnableAspectJAutoProxy(proxyTargetClass = true) //配置文件中  //proxyTargetClass = true代理创建方式的切换 把jdk切换成cglib
public class AppConfig {
}

TestAOP:

package com.baizhiedu;

import com.baizhiedu.aop.AppConfig;
import com.baizhiedu.aop.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestAOP {
    @Test
    public void test1(){
        ApplicationContext ctx =new AnnotationConfigApplicationContext(AppConfig.class);
        UserService userServiceImpl=(UserService)ctx.getBean("userServiceImpl");

        userServiceImpl.register();
        userServiceImpl.login();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值