告知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();
}
}