Java Code Examples for org.springframework.aop.MethodBeforeAdvice

The following examples show how to use org.springframework.aop.MethodBeforeAdvice. These examples are extracted from open source projects. 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
@Test
public void testCanGetStaticPartFromJoinPoint() {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart();
			assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart());
			assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind());
			assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature());
			assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	// Any call will do
	itb.getAge();
}
 
Example 2
Source Project: spring-analysis-note   Source File: AbstractAopProxyTests.java    License: MIT License 6 votes vote down vote up
/**
 * Check that the string is informative.
 */
@Test
public void testProxyConfigString() {
	TestBean target = new TestBean();
	ProxyFactory pc = new ProxyFactory(target);
	pc.setInterfaces(ITestBean.class);
	pc.addAdvice(new NopInterceptor());
	MethodBeforeAdvice mba = new CountingBeforeAdvice();
	Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut(), mba);
	pc.addAdvisor(advisor);
	ITestBean proxied = (ITestBean) createProxy(pc);

	String proxyConfigString = ((Advised) proxied).toProxyConfigString();
	assertTrue(proxyConfigString.contains(advisor.toString()));
	assertTrue(proxyConfigString.contains("1 interface"));
}
 
Example 3
@Test
public void testCanGetStaticPartFromJoinPoint() {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart();
			assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart());
			assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind());
			assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature());
			assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	// Any call will do
	itb.getAge();
}
 
Example 4
Source Project: java-technology-stack   Source File: AbstractAopProxyTests.java    License: MIT License 6 votes vote down vote up
/**
 * Check that the string is informative.
 */
@Test
public void testProxyConfigString() {
	TestBean target = new TestBean();
	ProxyFactory pc = new ProxyFactory(target);
	pc.setInterfaces(ITestBean.class);
	pc.addAdvice(new NopInterceptor());
	MethodBeforeAdvice mba = new CountingBeforeAdvice();
	Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut(), mba);
	pc.addAdvisor(advisor);
	ITestBean proxied = (ITestBean) createProxy(pc);

	String proxyConfigString = ((Advised) proxied).toProxyConfigString();
	assertTrue(proxyConfigString.contains(advisor.toString()));
	assertTrue(proxyConfigString.contains("1 interface"));
}
 
Example 5
Source Project: BlogManagePlatform   Source File: ParamLogAdvisor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * AOP切点
 * @author Frodez
 * @date 2019-05-10
 */
@Override
public Advice getAdvice() {
	/**
	 * 打印参数到日志
	 * @param JoinPoint AOP切点
	 * @author Frodez
	 * @date 2019-01-12
	 */
	return (MethodBeforeAdvice) (method, args, target) -> {
		Parameter[] parameters = method.getParameters();
		Map<String, Object> paramMap = new HashMap<>(parameters.length);
		for (int i = 0; i < parameters.length; ++i) {
			paramMap.put(parameters[i].getName(), args[i]);
		}
		log.info("{} 请求参数:{}", ReflectUtil.fullName(method), JSONUtil.string(paramMap));
	};
}
 
Example 6
@Test
public void testCanGetStaticPartFromJoinPoint() {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, Object target) throws Throwable {
			StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart();
			assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart());
			assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind());
			assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature());
			assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	// Any call will do
	itb.getAge();
}
 
Example 7
/**
 * Check that the string is informative.
 */
@Test
public void testProxyConfigString() {
	TestBean target = new TestBean();
	ProxyFactory pc = new ProxyFactory(target);
	pc.setInterfaces(new Class<?>[] {ITestBean.class});
	pc.addAdvice(new NopInterceptor());
	MethodBeforeAdvice mba = new CountingBeforeAdvice();
	Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut(), mba);
	pc.addAdvisor(advisor);
	ITestBean proxied = (ITestBean) createProxy(pc);

	String proxyConfigString = ((Advised) proxied).toProxyConfigString();
	assertTrue(proxyConfigString.indexOf(advisor.toString()) != -1);
	assertTrue(proxyConfigString.indexOf("1 interface") != -1);
}
 
Example 8
@Test
public void toShortAndLongStringFormedCorrectly() throws Exception {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			// makeEncSJP, although meant for computing the enclosing join point,
			// it serves our purpose here
			JoinPoint.StaticPart aspectJVersionJp = Factory.makeEncSJP(method);
			JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();

			assertEquals(aspectJVersionJp.getSignature().toLongString(), jp.getSignature().toLongString());
			assertEquals(aspectJVersionJp.getSignature().toShortString(), jp.getSignature().toShortString());
			assertEquals(aspectJVersionJp.getSignature().toString(), jp.getSignature().toString());

			assertEquals(aspectJVersionJp.toLongString(), jp.toLongString());
			assertEquals(aspectJVersionJp.toShortString(), jp.toShortString());
			assertEquals(aspectJVersionJp.toString(), jp.toString());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	itb.getAge();
	itb.setName("foo");
	itb.getDoctor();
	itb.getStringArray();
	itb.getSpouse();
	itb.setSpouse(new TestBean());
	try {
		itb.unreliableFileOperation();
	}
	catch (IOException ex) {
		// we don't really care...
	}
}
 
Example 9
public TestBeanAdvisor() {
	setAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			++count;
		}
	});
}
 
Example 10
@Test
public void toShortAndLongStringFormedCorrectly() throws Exception {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			// makeEncSJP, although meant for computing the enclosing join point,
			// it serves our purpose here
			JoinPoint.StaticPart aspectJVersionJp = Factory.makeEncSJP(method);
			JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();

			assertEquals(aspectJVersionJp.getSignature().toLongString(), jp.getSignature().toLongString());
			assertEquals(aspectJVersionJp.getSignature().toShortString(), jp.getSignature().toShortString());
			assertEquals(aspectJVersionJp.getSignature().toString(), jp.getSignature().toString());

			assertEquals(aspectJVersionJp.toLongString(), jp.toLongString());
			assertEquals(aspectJVersionJp.toShortString(), jp.toShortString());
			assertEquals(aspectJVersionJp.toString(), jp.toString());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	itb.getAge();
	itb.setName("foo");
	itb.getDoctor();
	itb.getStringArray();
	itb.getSpouse();
	itb.setSpouse(new TestBean());
	try {
		itb.unreliableFileOperation();
	}
	catch (IOException ex) {
		// we don't really care...
	}
}
 
Example 11
public TestBeanAdvisor() {
	setAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
			++count;
		}
	});
}
 
Example 12
public SyntheticInstantiationAdvisor(final MetadataAwareAspectInstanceFactory aif) {
	super(aif.getAspectMetadata().getPerClausePointcut(), new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, Object target) {
			// Simply instantiate the aspect
			aif.getAspectInstance();
		}
	});
}
 
Example 13
Source Project: hsweb-framework   Source File: RateLimiterAopAdvisor.java    License: Apache License 2.0 5 votes vote down vote up
public RateLimiterAopAdvisor(RateLimiterManager rateLimiterManager) {
    setAdvice((MethodBeforeAdvice) (method, args, target) -> {
        String[] names = nameDiscoverer.getParameterNames(method);
        RateLimiter limiter = Optional.ofNullable(AnnotationUtils.findAnnotation(method, RateLimiter.class))
                .orElseGet(() -> AnnotationUtils.findAnnotation(ClassUtils.getUserClass(target), RateLimiter.class));
        if (limiter != null) {
            List<String> keyExpressionList = new ArrayList<>(Arrays.asList(limiter.key()));
            if (keyExpressionList.isEmpty()) {
                keyExpressionList.add(method.toString());
            }
            for (String keyExpress : keyExpressionList) {
                if (keyExpress.contains("${")) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("user", Authentication.current().map(Authentication::getUser).orElse(null));
                    for (int i = 0; i < args.length; i++) {
                        params.put(names.length > i ? names[i] : "arg" + i, args[i]);
                        params.put("arg" + i, args[i]);

                    }
                    keyExpress = ExpressionUtils.analytical(keyExpress, params, "spel");
                }
                log.debug("do rate limiter:[{}]. ", keyExpress);
                boolean success = rateLimiterManager
                        .getRateLimiter(keyExpress, limiter.permits(), limiter.timeUnit())
                        .tryAcquire(limiter.acquire(), limiter.acquireTimeUnit());
                if (!success) {
                    throw new TimeoutException("请求超时");
                }
            }
        }
    });
}
 
Example 14
public SyntheticInstantiationAdvisor(final MetadataAwareAspectInstanceFactory aif) {
	super(aif.getAspectMetadata().getPerClausePointcut(), new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, Object target) {
			// Simply instantiate the aspect
			aif.getAspectInstance();
		}
	});
}
 
Example 15
@Test
public void toShortAndLongStringFormedCorrectly() throws Exception {
	final Object raw = new TestBean();
	ProxyFactory pf = new ProxyFactory(raw);
	pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
	pf.addAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, Object target) throws Throwable {
			// makeEncSJP, although meant for computing the enclosing join point,
			// it serves our purpose here
			JoinPoint.StaticPart aspectJVersionJp = Factory.makeEncSJP(method);
			JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();

			assertEquals(aspectJVersionJp.getSignature().toLongString(), jp.getSignature().toLongString());
			assertEquals(aspectJVersionJp.getSignature().toShortString(), jp.getSignature().toShortString());
			assertEquals(aspectJVersionJp.getSignature().toString(), jp.getSignature().toString());

			assertEquals(aspectJVersionJp.toLongString(), jp.toLongString());
			assertEquals(aspectJVersionJp.toShortString(), jp.toShortString());
			assertEquals(aspectJVersionJp.toString(), jp.toString());
		}
	});
	ITestBean itb = (ITestBean) pf.getProxy();
	itb.getAge();
	itb.setName("foo");
	itb.getDoctor();
	itb.getStringArray();
	itb.getSpouse();
	itb.setSpouse(new TestBean());
	try {
		itb.unreliableFileOperation();
	} catch (IOException ex) {
		// we don't realy care...
	}
}
 
Example 16
public TestBeanAdvisor() {
	setAdvice(new MethodBeforeAdvice() {
		@Override
		public void before(Method method, Object[] args, Object target) throws Throwable {
			++count;
		}
	});
}
 
Example 17
public SyntheticInstantiationAdvisor(final MetadataAwareAspectInstanceFactory aif) {
	super(aif.getAspectMetadata().getPerClausePointcut(), (MethodBeforeAdvice)
			(method, args, target) -> aif.getAspectInstance());
}
 
Example 18
Source Project: spring-analysis-note   Source File: MethodBeforeAdviceAdapter.java    License: MIT License 4 votes vote down vote up
@Override
public boolean supportsAdvice(Advice advice) {
	return (advice instanceof MethodBeforeAdvice);
}
 
Example 19
Source Project: spring-analysis-note   Source File: MethodBeforeAdviceAdapter.java    License: MIT License 4 votes vote down vote up
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
	MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
	return new MethodBeforeAdviceInterceptor(advice);
}
 
Example 20
/**
 * Create a new MethodBeforeAdviceInterceptor for the given advice.
 * @param advice the MethodBeforeAdvice to wrap
 */
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
	Assert.notNull(advice, "Advice must not be null");
	this.advice = advice;
}
 
Example 21
@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 22
public SyntheticInstantiationAdvisor(final MetadataAwareAspectInstanceFactory aif) {
	super(aif.getAspectMetadata().getPerClausePointcut(), (MethodBeforeAdvice)
			(method, args, target) -> aif.getAspectInstance());
}
 
Example 23
Source Project: java-technology-stack   Source File: MethodBeforeAdviceAdapter.java    License: MIT License 4 votes vote down vote up
@Override
public boolean supportsAdvice(Advice advice) {
	return (advice instanceof MethodBeforeAdvice);
}
 
Example 24
Source Project: java-technology-stack   Source File: MethodBeforeAdviceAdapter.java    License: MIT License 4 votes vote down vote up
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
	MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
	return new MethodBeforeAdviceInterceptor(advice);
}
 
Example 25
/**
 * Create a new MethodBeforeAdviceInterceptor for the given advice.
 * @param advice the MethodBeforeAdvice to wrap
 */
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
	Assert.notNull(advice, "Advice must not be null");
	this.advice = advice;
}
 
Example 26
@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 27
@Override
public boolean supportsAdvice(Advice advice) {
	return (advice instanceof MethodBeforeAdvice);
}
 
Example 28
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
	MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
	return new MethodBeforeAdviceInterceptor(advice);
}
 
Example 29
/**
 * Create a new MethodBeforeAdviceInterceptor for the given advice.
 * @param advice the MethodBeforeAdvice to wrap
 */
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
	Assert.notNull(advice, "Advice must not be null");
	this.advice = advice;
}
 
Example 30
@Override
public boolean supportsAdvice(Advice advice) {
	return (advice instanceof MethodBeforeAdvice);
}