原来在springAOP的用法中,只有代理的类才会被切入,我们在controller层调用service的方法的时候,是可以被切入的,但是如果我们在service层 A方法中,调用B方法,切点切的是B方法,那么这时候是不会切入的,解决办法就是如上所示,在A方法中使用((Service)AopContext.currentProxy()).B() 来调用B方法,这样一来,就能切入了!
1|0AopContext.currentProxy()该用法的意义
具体的用法在下面的代码中可以体会:
@Configuration @ComponentScan("com.dalianpai.spring5.aop") @EnableAspectJAutoProxy(exposeProxy = true)//开启spring注解aop配置的支持 public class SpringConfiguration { } public class User implements Serializable { private String id; private String username; private String password; private String email; private Date birthday; private String gender; private String mobile; private String nickname; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } } @Service("userService") public class UserServiceImpl implements UserService { @Override public void saveUser(User user) { System.out.println("执行了保存用户"+user); } @Override public void saveAllUser(List<User> users) { for(User user : users){ UserService proxyUserServiceImpl = (UserService)AopContext.currentProxy(); proxyUserServiceImpl.saveUser(user); } } } public interface UserService { /** * 模拟保存用户 * @param user */ void saveUser(User user); /** * 批量保存用户 * @param users */ void saveAllUser(List<User> users); } @Component @Aspect//表明当前类是一个切面类 public class LogUtil { /** * 用于配置当前方法是一个前置通知 */ @Before("execution(* com.dalianpai.spring5.aop.service.impl.*.saveUser(..))") public void printLog(){ System.out.println("执行打印日志的功能"); } }
测试类:
public class SpringEnableAspecctJAutoProxyTest { public static void main(String[] args) { //1.创建容器 AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class); //2.获取对象 UserService userService = ac.getBean("userService",UserService.class); //3.执行方法 User user = new User(); user.setId("1"); user.setUsername("test"); List<User> users = new ArrayList<>(); users.add(user); userService.saveAllUser(users); } }
如果去掉这行UserService proxyUserServiceImpl = (UserService)AopContext.currentProxy();