org.springframework.aop.framework.AopContext Java Examples
The following examples show how to use
org.springframework.aop.framework.AopContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserServiceImpl.java From thinking-in-spring with Apache License 2.0 | 6 votes |
/** * 使用事务非常容易犯以下错误: * 1)在同一个类中,a调用b,在b上面新开了一个事务,以为b上的事务生效了,其实是不生效的, * 因为事务基于aop实现,是通过代理对象完成事务包裹的,必须通过代理对象调用,事务才会生效, * 同一个类中,a调b,相当于this.a,只是一个普通对象调用,没有事务,很多人容易犯这个错误, * 老坑了。 * 2)事务方法必须为public的,否则事务也不会生效。 * * @author yihonglei * @date 2019/1/15 11:53 */ @Override @Transactional(propagation = Propagation.REQUIRED) public void a(String userName) { // 插入user 记录 jdbcTemplate.update("INSERT INTO `user` (userName) VALUES(?)", userName); // 事务未生效:同类中a直接调用b方法,相当于b的代码直接写在a里面,事务要基于代理对象调用才有效,所以b上的事务是无效的。 // b(userName, 10000); // 事务生效:获取代理对象,基于代理对象调用,事务才能生效。 UserService proxy = (UserService) AopContext.currentProxy(); proxy.b(userName, 10000); // 人为报错 int i = 1 / 0; }
Example #2
Source File: BaseMovableService.java From es with Apache License 2.0 | 6 votes |
public void reweight() { int batchSize = 100; Sort sort = new Sort(Sort.Direction.DESC, "weight"); Pageable pageable = new PageRequest(0, batchSize, sort); Page<M> page = findAll(pageable); do { //doReweight需要requiresNew事务 ((BaseMovableService) AopContext.currentProxy()).doReweight(page); RepositoryHelper.clear(); if (page.isLastPage()) { break; } pageable = new PageRequest((pageable.getPageNumber() + 1) * batchSize, batchSize, sort); page = findAll(pageable); } while (true); }
Example #3
Source File: MessageApiImpl.java From es with Apache License 2.0 | 6 votes |
@Async @Override public void sendSystemMessageToAllUser(Message message) { //TODO 变更实现策略 使用异步发送 int pn = 0; int pageSize = 100; Pageable pageable = null; Page<User> page = null; do { pageable = new PageRequest(pn++, pageSize); page = userService.findAll(pageable); try { ((MessageApiImpl) AopContext.currentProxy()).doSendSystemMessage(page.getContent(), message); } catch (Exception e) { LogUtils.logError("send system message to all user error", e); } RepositoryHelper.clear(); } while (page.hasNextPage()); }
Example #4
Source File: AuthRelationClearTask.java From es with Apache License 2.0 | 6 votes |
/** * 清除删除的角色对应的关系 */ public void clearDeletedAuthRelation() { Set<Long> allRoleIds = findAllRoleIds(); final int PAGE_SIZE = 100; int pn = 0; Page<Auth> authPage = null; do { Pageable pageable = new PageRequest(pn++, PAGE_SIZE); authPage = authService.findAll(pageable); //开启新事物清除 try { AuthRelationClearTask authRelationClearService = (AuthRelationClearTask) AopContext.currentProxy(); authRelationClearService.doClear(authPage.getContent(), allRoleIds); } catch (Exception e) { //出异常也无所谓 LogUtils.logError("clear auth relation error", e); } //清空会话 RepositoryHelper.clear(); } while (authPage.hasNextPage()); }
Example #5
Source File: RoleClearRelationTask.java From es with Apache License 2.0 | 6 votes |
/** * 清除删除的角色对应的关系 */ public void clearDeletedRoleRelation() { final int PAGE_SIZE = 100; int pn = 0; Page<Role> rolePage = null; do { Pageable pageable = new PageRequest(pn++, PAGE_SIZE); rolePage = roleService.findAll(pageable); //开启新事物清除 try { RoleClearRelationTask roleClearRelationTask = (RoleClearRelationTask) AopContext.currentProxy(); roleClearRelationTask.doClear(rolePage.getContent()); } catch (Exception e) { //出异常也无所谓 LogUtils.logError("clear role relation error", e); } //清空会话 RepositoryHelper.clear(); } while (rolePage.hasNextPage()); }
Example #6
Source File: BrokerMonitorServiceImpl.java From joyqueue with Apache License 2.0 | 6 votes |
@Override public BrokerMonitorRecord find(Subscribe subscribe, boolean active) { if(active){ List<BrokerMonitorRecord> brokerMonitorRecords= findMonitorOnPartitionGroupsForTopicApp(subscribe); // BrokerMonitorRecord brokerMonitorRecord=merge(subscribe,brokerMonitorRecords); // not contain connection and retry info if(!NullUtil.isEmpty(brokerMonitorRecord)) { BrokerMonitorRecord retryAndConnectionInfo = ((BrokerMonitorService)AopContext.currentProxy()).find(subscribe);// optimize if(!NullUtil.isEmpty(retryAndConnectionInfo)) { brokerMonitorRecord.setRetry(retryAndConnectionInfo.getRetry()); // upset brokerMonitorRecord.setConnections(retryAndConnectionInfo.getConnections()); } } return brokerMonitorRecord; }else{ return find(subscribe); } }
Example #7
Source File: EnableAspectJAutoProxyTests.java From java-technology-stack with MIT License | 5 votes |
@Bean public FooService fooServiceImpl(final ApplicationContext context) { return new FooServiceImpl() { @Override public String foo(int id) { assertNotNull(AopContext.currentProxy()); return super.foo(id); } @Override protected FooDao fooDao() { return context.getBean(FooDao.class); } }; }
Example #8
Source File: MessageClearTask.java From es with Apache License 2.0 | 5 votes |
public void autoClearExpiredOrDeletedmMessage() { MessageClearTask messageClearTask = (MessageClearTask) AopContext.currentProxy(); //1、收件箱、发件箱状态修改为垃圾箱状态 messageClearTask.doClearInOrOutBox(); //2、垃圾箱状态改为已删除状态 messageClearTask.doClearTrashBox(); //3、物理删除那些已删除的(即收件人和发件人 同时都删除了的) messageClearTask.doClearDeletedMessage(); }
Example #9
Source File: TransferServiceImpl.java From Hands-On-High-Performance-with-Spring-5 with MIT License | 5 votes |
@Override public boolean transfer(Account source, Account dest, Double amount) { // transfer amount from source account to dest account LOGGER.info("Tranfering " + amount + " from " + source.getAccountName() + " to " + dest.getAccountName()); ((TransferService)(AopContext.currentProxy())).checkBalance(source); return true; }
Example #10
Source File: EnableAspectJAutoProxyTests.java From spring-analysis-note with MIT License | 5 votes |
@Bean public FooService fooServiceImpl(final ApplicationContext context) { return new FooServiceImpl() { @Override public String foo(int id) { assertNotNull(AopContext.currentProxy()); return super.foo(id); } @Override protected FooDao fooDao() { return context.getBean(FooDao.class); } }; }
Example #11
Source File: UserAuthService.java From es with Apache License 2.0 | 5 votes |
/** * 根据角色获取 权限字符串 如sys:admin * * @param user * @return */ public Set<String> findStringPermissions(User user) { Set<String> permissions = Sets.newHashSet(); Set<Role> roles = ((UserAuthService) AopContext.currentProxy()).findRoles(user); for (Role role : roles) { for (RoleResourcePermission rrp : role.getResourcePermissions()) { Resource resource = resourceService.findOne(rrp.getResourceId()); String actualResourceIdentity = resourceService.findActualResourceIdentity(resource); //不可用 即没查到 或者标识字符串不存在 if (resource == null || StringUtils.isEmpty(actualResourceIdentity) || Boolean.FALSE.equals(resource.getShow())) { continue; } for (Long permissionId : rrp.getPermissionIds()) { Permission permission = permissionService.findOne(permissionId); //不可用 if (permission == null || Boolean.FALSE.equals(permission.getShow())) { continue; } permissions.add(actualResourceIdentity + ":" + permission.getPermission()); } } } return permissions; }
Example #12
Source File: UserAuthService.java From es with Apache License 2.0 | 5 votes |
public Set<String> findStringRoles(User user) { Set<Role> roles = ((UserAuthService) AopContext.currentProxy()).findRoles(user); return Sets.newHashSet(Collections2.transform(roles, new Function<Role, String>() { @Override public String apply(Role input) { return input.getRole(); } })); }
Example #13
Source File: UserClearRelationTask.java From es with Apache License 2.0 | 5 votes |
/** * 清除删除的用户-组织机构/工作职务对应的关系 */ public void clearDeletedUserRelation() { //删除用户不存在的情况的UserOrganizationJob(比如手工从数据库物理删除)。。 userService.deleteUserOrganizationJobOnNotExistsUser(); Page<UserOrganizationJob> page = null; int pn = 0; final int PAGE_SIZE = 100; Pageable pageable = null; do { pageable = new PageRequest(pn++, PAGE_SIZE); page = userService.findUserOrganizationJobOnNotExistsOrganizationOrJob(pageable); //开启新事物清除 try { UserClearRelationTask userClearRelationTask = (UserClearRelationTask) AopContext.currentProxy(); userClearRelationTask.doClear(page.getContent()); } catch (Exception e) { //出异常也无所谓 LogUtils.logError("clear user relation error", e); } //清空会话 RepositoryHelper.clear(); } while (page.hasNextPage()); }
Example #14
Source File: UserService.java From es with Apache License 2.0 | 5 votes |
public void changeStatus(User opUser, Long[] ids, UserStatus newStatus, String reason) { UserService proxyUserService = (UserService) AopContext.currentProxy(); for (Long id : ids) { User user = findOne(id); proxyUserService.changeStatus(opUser, user, newStatus, reason); UserLogUtils.log( user.getUsername(), "changeStatus", "admin user {} change status!", opUser.getUsername()); } }
Example #15
Source File: UserService.java From es with Apache License 2.0 | 5 votes |
public void changePassword(User opUser, Long[] ids, String newPassword) { UserService proxyUserService = (UserService) AopContext.currentProxy(); for (Long id : ids) { User user = findOne(id); proxyUserService.changePassword(user, newPassword); UserLogUtils.log( user.getUsername(), "changePassword", "admin user {} change password!", opUser.getUsername()); } }
Example #16
Source File: MethodInvocationProceedingJoinPointTests.java From spring-analysis-note with MIT License | 4 votes |
@Test public void testCanGetMethodSignatureFromJoinPoint() { final Object raw = new TestBean(); // Will be set by advice during a method call final int newAge = 23; ProxyFactory pf = new ProxyFactory(raw); pf.setExposeProxy(true); pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR); pf.addAdvice(new MethodBeforeAdvice() { private int depth; @Override public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); assertTrue("Method named in toString", jp.toString().contains(method.getName())); // Ensure that these don't cause problems jp.toShortString(); jp.toLongString(); assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget()); assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())); ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis(); assertTrue(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis())); assertNotSame(target, thisProxy); // Check getting again doesn't cause a problem assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis()); // Try reentrant call--will go through this advice. // Be sure to increment depth to avoid infinite recursion if (depth++ == 0) { // Check that toString doesn't cause a problem thisProxy.toString(); // Change age, so this will be returned by invocation thisProxy.setAge(newAge); assertEquals(newAge, thisProxy.getAge()); } assertSame(AopContext.currentProxy(), thisProxy); assertSame(target, raw); assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()); assertEquals(method.getModifiers(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()); MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature(); assertSame("Return same MethodSignature repeatedly", msig, AbstractAspectJAdvice.currentJoinPoint().getSignature()); assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(), AbstractAspectJAdvice.currentJoinPoint()); assertEquals(method.getDeclaringClass(), msig.getDeclaringType()); assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())); assertEquals(method.getReturnType(), msig.getReturnType()); assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())); msig.toLongString(); msig.toShortString(); } }); ITestBean itb = (ITestBean) pf.getProxy(); // Any call will do assertEquals("Advice reentrantly set age", newAge, itb.getAge()); }
Example #17
Source File: MethodInvocationProceedingJoinPointTests.java From java-technology-stack with MIT License | 4 votes |
@Test public void testCanGetMethodSignatureFromJoinPoint() { final Object raw = new TestBean(); // Will be set by advice during a method call final int newAge = 23; ProxyFactory pf = new ProxyFactory(raw); pf.setExposeProxy(true); pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR); pf.addAdvice(new MethodBeforeAdvice() { private int depth; @Override public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); assertTrue("Method named in toString", jp.toString().contains(method.getName())); // Ensure that these don't cause problems jp.toShortString(); jp.toLongString(); assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget()); assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())); ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis(); assertTrue(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis())); assertNotSame(target, thisProxy); // Check getting again doesn't cause a problem assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis()); // Try reentrant call--will go through this advice. // Be sure to increment depth to avoid infinite recursion if (depth++ == 0) { // Check that toString doesn't cause a problem thisProxy.toString(); // Change age, so this will be returned by invocation thisProxy.setAge(newAge); assertEquals(newAge, thisProxy.getAge()); } assertSame(AopContext.currentProxy(), thisProxy); assertSame(target, raw); assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()); assertEquals(method.getModifiers(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()); MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature(); assertSame("Return same MethodSignature repeatedly", msig, AbstractAspectJAdvice.currentJoinPoint().getSignature()); assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(), AbstractAspectJAdvice.currentJoinPoint()); assertEquals(method.getDeclaringClass(), msig.getDeclaringType()); assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())); assertEquals(method.getReturnType(), msig.getReturnType()); assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())); msig.toLongString(); msig.toShortString(); } }); ITestBean itb = (ITestBean) pf.getProxy(); // Any call will do assertEquals("Advice reentrantly set age", newAge, itb.getAge()); }
Example #18
Source File: UserService.java From es with Apache License 2.0 | 4 votes |
public User login(String username, String password) { if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { UserLogUtils.log( username, "loginError", "username is empty"); throw new UserNotExistsException(); } //密码如果不在指定范围内 肯定错误 if (password.length() < User.PASSWORD_MIN_LENGTH || password.length() > User.PASSWORD_MAX_LENGTH) { UserLogUtils.log( username, "loginError", "password length error! password is between {} and {}", User.PASSWORD_MIN_LENGTH, User.PASSWORD_MAX_LENGTH); throw new UserPasswordNotMatchException(); } User user = null; //此处需要走代理对象,目的是能走缓存切面 UserService proxyUserService = (UserService) AopContext.currentProxy(); if (maybeUsername(username)) { user = proxyUserService.findByUsername(username); } if (user == null && maybeEmail(username)) { user = proxyUserService.findByEmail(username); } if (user == null && maybeMobilePhoneNumber(username)) { user = proxyUserService.findByMobilePhoneNumber(username); } if (user == null || Boolean.TRUE.equals(user.getDeleted())) { UserLogUtils.log( username, "loginError", "user is not exists!"); throw new UserNotExistsException(); } passwordService.validate(user, password); if (user.getStatus() == UserStatus.blocked) { UserLogUtils.log( username, "loginError", "user is blocked!"); throw new UserBlockedException(userStatusHistoryService.getLastReason(user)); } UserLogUtils.log( username, "loginSuccess", ""); return user; }
Example #19
Source File: ExcelDataService.java From es with Apache License 2.0 | 4 votes |
@Async public void initOneMillionData(final User user) { ExcelDataService proxy = (ExcelDataService) AopContext.currentProxy(); long beginTime = System.currentTimeMillis(); getExcelDataRepository().truncate(); final int ONE_MILLION = 1000000; //100w for(int i = batchSize; i <= ONE_MILLION; i += batchSize) { //不能使用AopContext.currentProxy() 因为task:annotation-driven没有暴露proxy。。 proxy.doBatchSave(i - batchSize); } long endTime = System.currentTimeMillis(); Map<String, Object> context = Maps.newHashMap(); context.put("seconds", (endTime - beginTime) / 1000); notificationApi.notify(user.getId(), "excelInitDataSuccess", context); }
Example #20
Source File: MethodInvocationProceedingJoinPointTests.java From spring4-understanding with Apache License 2.0 | 4 votes |
@Test public void testCanGetMethodSignatureFromJoinPoint() { final Object raw = new TestBean(); // Will be set by advice during a method call final int newAge = 23; ProxyFactory pf = new ProxyFactory(raw); pf.setExposeProxy(true); pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR); pf.addAdvice(new MethodBeforeAdvice() { private int depth; @Override public void before(Method method, Object[] args, Object target) throws Throwable { JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); assertTrue("Method named in toString", jp.toString().contains(method.getName())); // Ensure that these don't cause problems jp.toShortString(); jp.toLongString(); assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget()); assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())); ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis(); assertTrue(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis())); assertNotSame(target, thisProxy); // Check getting again doesn't cause a problem assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis()); // Try reentrant call--will go through this advice. // Be sure to increment depth to avoid infinite recursion if (depth++ == 0) { // Check that toString doesn't cause a problem thisProxy.toString(); // Change age, so this will be returned by invocation thisProxy.setAge(newAge); assertEquals(newAge, thisProxy.getAge()); } assertSame(AopContext.currentProxy(), thisProxy); assertSame(target, raw); assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()); assertEquals(method.getModifiers(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()); MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature(); assertSame("Return same MethodSignature repeatedly", msig, AbstractAspectJAdvice.currentJoinPoint().getSignature()); assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(), AbstractAspectJAdvice.currentJoinPoint()); assertEquals(method.getDeclaringClass(), msig.getDeclaringType()); assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())); assertEquals(method.getReturnType(), msig.getReturnType()); assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())); msig.toLongString(); msig.toShortString(); } }); ITestBean itb = (ITestBean) pf.getProxy(); // Any call will do assertEquals("Advice reentrantly set age", newAge, itb.getAge()); }
Example #21
Source File: GenericService.java From Aooms with Apache License 2.0 | 4 votes |
public <T> T proxy(Class<T> obj){ return ((T) AopContext.currentProxy()); }
Example #22
Source File: SpringUtils.java From runscore with Apache License 2.0 | 2 votes |
/** * 获取aop代理对象 * * @param invoker * @return */ @SuppressWarnings("unchecked") public static <T> T getAopProxy(T invoker) { return (T) AopContext.currentProxy(); }
Example #23
Source File: SpringUtils.java From supplierShop with MIT License | 2 votes |
/** * 获取aop代理对象 * * @param invoker * @return */ @SuppressWarnings("unchecked") public static <T> T getAopProxy(T invoker) { return (T) AopContext.currentProxy(); }
Example #24
Source File: SpringUtils.java From RuoYi with Apache License 2.0 | 2 votes |
/** * 获取aop代理对象 * * @param invoker * @return 代理对象 */ @SuppressWarnings("unchecked") public static <T> T getAopProxy(T invoker){ return (T) AopContext.currentProxy(); }
Example #25
Source File: AopContextHolder.java From Milkomeda with MIT License | 2 votes |
/** * 获得当前切面代理对象 * <br>使用前通过<code>@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)</code>开启代理曝露 * * @param clazz 当前类 * @param <T> 当前类型 * @return 代理对象 */ @SuppressWarnings("unchecked") public static <T> T self(Class<T> clazz) { return (T)AopContext.currentProxy(); }
Example #26
Source File: SpringUtils.java From DimpleBlog with Apache License 2.0 | 2 votes |
/** * 获取aop代理对象 * * @param invoker * @return */ @SuppressWarnings("unchecked") public static <T> T getAopProxy(T invoker) { return (T) AopContext.currentProxy(); }
Example #27
Source File: SpringUtils.java From RuoYi-Vue with MIT License | 2 votes |
/** * 获取aop代理对象 * * @param invoker * @return */ @SuppressWarnings("unchecked") public static <T> T getAopProxy(T invoker) { return (T) AopContext.currentProxy(); }