What is the difference between @AfterReturning(pointcut)
and @AfterReturning(value)
@AfterReturning(pointcut = "execution(* my.java.model.Triangle.myTest*(param))", returning = "returnedString", argNames = "param,returnedString")
public void afterReturningAdvice(String param, String returnedString) {
System.out.println("Executing after function advice that accepts the input " + param + " and returns " + returnedString);
}
The above method results in Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 name binding only allowed in target, this, and args pcds
.
It works fine after replacing the above code with
@AfterReturning(value = "(* my.java.model.Triangle.myTest*(*)) && args(param)", returning = "returnedString", argNames = "param,returnedString")
public void afterReturningAdvice(String param, String returnedString) {
System.out.println("Executing after function advice that accepts the input " + param + " and returns " + returnedString);
}
What is the difference between value and pointcut
Содержание
- @AfterReturning (pointcut) vs @AfterReturning (значение)
- 2 ответа
- IllegalArgumentException « Exception « Spring Q&A
- 1. Why is Java giving me an IllegalArgumentException? stackoverflow.com
- 4. java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut stackoverflow.com
- 5. Cache Abstraction IllegalArgumentException when debug symbols off forum.springsource.org
- 6. java.lang.IllegalArgumentException forum.springsource.org
- 7. DateTimeFormat — IllegalArgumentException forum.springsource.org
- 8. Errrorrr :java.lang.IllegalArgumentException: Cannot parse date value «-1» for «Expir forum.springsource.org
- 9. IllegalArgumentException in CustomizableTraceInterceptor forum.springsource.org
- 10. IllegalArgumentException on Tomcat startup forum.springsource.org
- 11. Understanding an IllegalArgumentException forum.springsource.org
- 13. Spring -Weblogic java.lang.IllegalArgumentException forum.springsource.org
- 14. IllegalArgumentException when referencing another pointcut forum.springsource.org
- 15. Why IllegalArgumentException thrown by InitializingBeans? forum.springsource.org
- 16. JUnit test gets IllegalArgumentException forum.springsource.org
- 17. java.lang.IllegalArgumentException: No matching editors or conversion forum.springsource.org
- 18. IllegalArgumentException during aspect method invoke forum.springsource.org
- 19. causes IllegalArgumentException on Resin only forum.springsource.org
- 20. IllegalArgumentException occurred calling getter method forum.springsource.org
- 21. java.lang.IllegalArgumentException: Location pattern must not be null forum.springsource.org
- 22. java.lang.IllegalArgumentException forum.springsource.org
- 23. + => Cglib IllegalArgumentException forum.springsource.org
- 24. RMI Problem, java.lang.IllegalArgumentException forum.springsource.org
- 25. java.lang.IllegalArgumentException forum.springsource.org
- 26. TransactionProxy + Validator: IllegalArgumentException forum.springsource.org
- 27. [XT Ajax] IllegalArgumentException: setAttribute: Non-serializable attribut forum.springsource.org
- 28. java.lang.IllegalArgumentException: Removing a detached instance forum.springsource.org
- 29. $Proxy IllegalArgumentException forum.springsource.org
- 30. ‘IllegalArgumentException: SOAPElement expected’ with XmlBeans forum.springsource.org
- 31. java.lang.IllegalArgumentException: Superclass has no null constructors but no argume forum.springsource.org
- 32. IllegalArgumentException occurred calling getter forum.springsource.org
- 33. java.lang.IllegalArgumentException: Location pattern must not be null forum.springsource.org
- 34. java.lang.IllegalArgumentException: forum.springsource.org
- 35. java.lang.IllegalArgumentException: ‘items’ must not be null forum.springsource.org
- 37. IllegalArgumentException: name binding only allowed in target, this, and args pcds forum.springsource.org
- 38. Validation — Compare 2 Dates — IllegalArgumentException forum.springsource.org
- 39. IllegalArgumentException when creating FixedLengthTokenizer forum.springsource.org
- 40. Urgent Help Needed: java.lang.IllegalArgumentException: Cannot locate BeanDefinitionD forum.springsource.org
- 41. IllegalArgumentException trying to run PetClinicClientServer forum.springsource.org
- 42. IllegalArgumentException at WebSphereUowTransactionManager forum.springsource.org
- 44. java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] forum.springsource.org
- 45. IllegalArgumentException: ServletContext must not be null forum.springsource.org
- 46. Side effect of loglevel: java.lang.IllegalArgumentException: step execution is expect forum.springsource.org
- 47. HELP: java.lang.IllegalArgumentException does not support command class forum.springsource.org
- 49. Aspect code not working — IllegalArgumentException forum.springsource.org
- 50. @RequestMapping java.lang.IllegalArgumentException forum.springsource.org
- 51. java.lang.IllegalArgumentException: Cannot subclass final class class $Proxy112 forum.springsource.org
- 52. Error: IllegalArgumentException: Original must not be null forum.springsource.org
- 53. IllegalArgumentException: Cannot convert value of type [java.lang.String] to required forum.springsource.org
- 54. IllegalArgumentException at FilterInvocationDefinitionSource forum.springsource.org
- 55. IllegalArgumentException: class is not an enhanced class forum.springsource.org
- 56. IllegalArgumentException: error wildcard type pattern not allowed, must use type name forum.springsource.org
- 57. IllegalArgumentException: Method must not be null forum.springsource.org
- 58. IllegalArgumentException with ApplicationContextAware + Proxy forum.springsource.org
@AfterReturning (pointcut) vs @AfterReturning (значение)
В чем разница между @AfterReturning(pointcut) и @AfterReturning(value)
Вышеупомянутый метод приводит к Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 name binding only allowed in target, this, and args pcds .
Он отлично работает после замены приведенного выше кода на
В чем разница между value и pointcut
2 ответа
Фактически, при использовании выражения pointcut вы переопределяете литературное предложение value , если оно указано, вы можете скопировать свое выражение, которое указывает, где привязать совет от значения к pointcut и наоборот, отметьте здесь
Вы получаете исключение, потому что AfterReturning неявно связывает только возвращаемое значение, если вы хотите привязать какой-либо аргумент, вы должны добавить && args (param) к первому выражению:
Обратите внимание, что я также меняю execution(* my.java.model.Triangle.myTest*(param) на execution(* my.java.model.Triangle.myTest*(String) поскольку выполнение (..) не имеет ничего общего с аргументом привязки к совету, он соответствует только точкам соединения выполнения метода.
В pointcut вы можете связать аргументы метода, this() , target() , @annotation() . Это работает со всеми типами советов.
В @AfterReturning вы можете дополнительно привязать возвращаемое значение, а в @AfterThrowing — выброшенное исключение.
Аргументы метода и возвращаемое значение не следует путать друг с другом.
Источник
IllegalArgumentException « Exception « Spring Q&A
1. Why is Java giving me an IllegalArgumentException? stackoverflow.com
I’m using dwr and spring and I get this error: I found nothing helpful on Google, do you know why I’m getting this error? i am getting .
4. java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut stackoverflow.com
Thinker.java
package springdemo2; public interface Thinker
package springdemo2; public class Volunteer .
5. Cache Abstraction IllegalArgumentException when debug symbols off forum.springsource.org
Cache Abstraction IllegalArgumentException when debug symbols off I have been working with Spring Cache Abstraction in 3.1.0.M1. I’m using the @Cacheable annotation on a target method like so: @Cacheable(value=»books», key=»#name») public .
6. java.lang.IllegalArgumentException forum.springsource.org
java.lang.IllegalArgumentException:Cannot convert java.lang.String to java.sql.Date Hi i am getting above exception when inserting the values in the database, the detailed exception is, UserVO Constructor. Apr 26, 2011 1:54:36 PM org.apache.catalina.core.StandardWrapperValve invoke .
7. DateTimeFormat — IllegalArgumentException forum.springsource.org
DateTimeFormat — IllegalArgumentException In my domain class I have: Code: @NotNull @DateTimeFormat(iso=ISO.DATE) @Type(type=»org.jadira.usertype.dateandtime.joda.PersistentLocalDate») private LocalDate visit_date; If I enter a correctly formatted date eg. 01/01/2010 all is ok. And if I .
8. Errrorrr :java.lang.IllegalArgumentException: Cannot parse date value «-1» for «Expir forum.springsource.org
Dec 1st, 2011, 05:56 AM #1 adarshgp.nie View Profile View Forum Posts Private Message Member Join Date Nov 2011 Posts 31 Errrorrr :java.lang.IllegalArgumentException: Cannot parse date value «-1» for «Expir I .
9. IllegalArgumentException in CustomizableTraceInterceptor forum.springsource.org
IllegalArgumentException in CustomizableTraceInterceptor Just want to point out a problem with the org.springframework.aop.interceptor.CustomizableTr aceInterceptor We used it the following way: Code:
10. IllegalArgumentException on Tomcat startup forum.springsource.org
IllegalArgumentException on Tomcat startup Hello, When adding an acl voter to my decisionVoters in the accessDecisionManager, I always get a Code: java.lang.IllegalArgumentException: AccessDecisionManager does not support secure object class: class net.sf.acegisecurity.intercept.web.FilterInvocation .
11. Understanding an IllegalArgumentException forum.springsource.org
Understanding an IllegalArgumentException I have a view that ties several tables together. The H3 XML mapping: Code: forum.springsource.org
IllegalArgumentException during system shutdown Hello, We have a Interceptor that does performance logging. It simply logs a record before and after a method call. It works fine everwhere with one exception. .
13. Spring -Weblogic java.lang.IllegalArgumentException forum.springsource.org
Spring -Weblogic java.lang.IllegalArgumentException Hi, I’m trying to set defaultdestination for jmsTemplate and is giving me Failed to convert property value of type [weblogic.jms.client.JMSConnectionFactory] to required type [javax.jms.Destination] for property ‘defaultDestination’ Can .
14. IllegalArgumentException when referencing another pointcut forum.springsource.org
Aug 30th, 2006, 09:40 AM #1 bemmi View Profile View Forum Posts Private Message Junior Member Join Date Aug 2006 Posts 8 IllegalArgumentException when referencing another pointcut I get an IllegalArgumentException .
15. Why IllegalArgumentException thrown by InitializingBeans? forum.springsource.org
Why IllegalArgumentException thrown by InitializingBeans? I am curious why many of the Spring classes that implement the InitializingBean interface throw exceptions of type IllegalArgumentException rather than some Spring-specific InitializationException. I realize .
16. JUnit test gets IllegalArgumentException forum.springsource.org
JUnit test gets IllegalArgumentException I am attempting to write JUnit test case for an application that is currently implemented as a servlet. The JUnit test case extends AbstractDependencyInjectionSpringContextTests overriding getConfigLocations(). I .
17. java.lang.IllegalArgumentException: No matching editors or conversion forum.springsource.org
java.lang.IllegalArgumentException: No matching editors or conversion Hi Im getting this error when trying to load up my page, anyone know what i might doing wrong? regards Prinsinn org.springframework.beans.factory.BeanCreationExce ption: Error creating .
18. IllegalArgumentException during aspect method invoke forum.springsource.org
IllegalArgumentException during aspect method invoke Using: Spring 2.0.1 JDK: 1.5 update 9 I’m stuck with an aspect problem which i doesn’t seem to work for me. Any help would be appreciated. .
19. causes IllegalArgumentException on Resin only forum.springsource.org
causes IllegalArgumentException on Resin only Hi I have in my applicationContext.xml. Only on Resin, I am getting the following error: org.springframework.beans.factory.BeanDefinitionSt oreException: Unexpected exception parsing XML document from ServletContext .
20. IllegalArgumentException occurred calling getter method forum.springsource.org
Jan 19th, 2007, 04:26 PM #1 mail2bansi View Profile View Forum Posts Private Message Senior Member Join Date May 2006 Posts 142 IllegalArgumentException occurred calling getter method Hibernate version: 3.1.2 Mapping .
21. java.lang.IllegalArgumentException: Location pattern must not be null forum.springsource.org
Feb 8th, 2007, 08:07 AM #1 garethwebber View Profile View Forum Posts Private Message Junior Member Join Date Feb 2007 Posts 7 java.lang.IllegalArgumentException: Location pattern must not be null Hi, I .
22. java.lang.IllegalArgumentException forum.springsource.org
Feb 12th, 2007, 02:45 PM #1 tan1981 View Profile View Forum Posts Private Message Junior Member Join Date Feb 2007 Posts 5 java.lang.IllegalArgumentException Hi, I am trying to create a Form .
23. + => Cglib IllegalArgumentException forum.springsource.org
24. RMI Problem, java.lang.IllegalArgumentException forum.springsource.org
RMI Problem, java.lang.IllegalArgumentException Hey, has anyone an idea what this error msg means? Code: Exception in thread «main» org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘remoteInfoBeanRMI’ defined in class path resource [a.xml]: .
25. java.lang.IllegalArgumentException forum.springsource.org
Jun 16th, 2007, 04:28 PM #1 thomas2004 View Profile View Forum Posts Private Message Senior Member Join Date Jun 2007 Posts 159 java.lang.IllegalArgumentException My entity vo looks as follow: Code: package .
26. TransactionProxy + Validator: IllegalArgumentException forum.springsource.org
TransactionProxy + Validator: IllegalArgumentException Hi everyone, I just refactored all Hibernate Daos to run through the openSessionInViewInterceptor to enable lazy-loading now everywhere. It all works fine except of the password change .
27. [XT Ajax] IllegalArgumentException: setAttribute: Non-serializable attribut forum.springsource.org
[XT Ajax] IllegalArgumentException: setAttribute: Non-serializable attribut Hi, Getting an exception due to non-serializable attribute. Come from where the errors are stored in the Session here (from DefaultValidationHandler.java): private void putNewErrors(AjaxSubmitEvent event, .
28. java.lang.IllegalArgumentException: Removing a detached instance forum.springsource.org
Aug 23rd, 2007, 10:15 PM #1 tirzaman View Profile View Forum Posts Private Message Junior Member Join Date Aug 2007 Posts 18 java.lang.IllegalArgumentException: Removing a detached instance Environment Spring 2, .
29. $Proxy IllegalArgumentException forum.springsource.org
$Proxy IllegalArgumentException I’m trying to inject a LocalSessionFactoryBean into another bean via dependency injection, and I am getting: Code: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘APSHibernateTemplateWrapper’ defined in ServletContext resource [/WEB-INF/hibernate-config.xml]: .
30. ‘IllegalArgumentException: SOAPElement expected’ with XmlBeans forum.springsource.org
‘IllegalArgumentException: SOAPElement expected’ with XmlBeans Hi, I use XmlBeans (2.3.0) as a (un)marshaller in Spring Web Services. A request is properly processed, but returned response causes: Code: 2007-09-23 17:41:41,015 DEBUG [org.myname.webservice.ChangeUserPasswordMarshallingEndpoint] .
31. java.lang.IllegalArgumentException: Superclass has no null constructors but no argume forum.springsource.org
java.lang.IllegalArgumentException: Superclass has no null constructors but no argume I am using Spring 2.0 with Hibernate 3.0/JPA. I am getting following error when creating a POJO class. java.lang.IllegalArgumentException: Superclass has no .
32. IllegalArgumentException occurred calling getter forum.springsource.org
Oct 5th, 2007, 03:40 PM #1 bscribner View Profile View Forum Posts Private Message Junior Member Join Date Oct 2007 Posts 2 IllegalArgumentException occurred calling getter Hi I’m currently having a .
33. java.lang.IllegalArgumentException: Location pattern must not be null forum.springsource.org
Oct 23rd, 2007, 07:40 AM #1 naveentsnts View Profile View Forum Posts Private Message Junior Member Join Date Jun 2007 Posts 5 java.lang.IllegalArgumentException: Location pattern must not be null Hello All, .
34. java.lang.IllegalArgumentException: forum.springsource.org
java.lang.IllegalArgumentException: Hi , I am trying to execute a stored procedure from Ibatis sql map and getting this exception » java.lang.IllegalArgumentException». Code : JAVA Map map = new HashMap(); map.put(«Single_Sign_on»,»SR22473″); BMSAuthorizationTOList .
35. java.lang.IllegalArgumentException: ‘items’ must not be null forum.springsource.org
java.lang.IllegalArgumentException: ‘items’ must not be null Getting the following error when trying to submit a form with a forum.springsource.org
Mar 11th, 2008, 06:59 AM #1 sandrine View Profile View Forum Posts Private Message Member Join Date Feb 2008 Posts 41 java.lang.IllegalArgumentException when exit code is NOOP Hi, I have a .
37. IllegalArgumentException: name binding only allowed in target, this, and args pcds forum.springsource.org
Mar 21st, 2008, 12:58 PM #1 Helena View Profile View Forum Posts Private Message Member Spring Team Join Date Dec 2007 Posts 90 IllegalArgumentException: name binding only allowed in target, this, .
38. Validation — Compare 2 Dates — IllegalArgumentException forum.springsource.org
Validation — Compare 2 Dates — IllegalArgumentException Hi, i what to compare two dates. @RegExp(applyIf=»teilStundungVon HAS TEXT and teilStundungBis HAS TEXT and teilStundungVon => teilStundungBis»,value=»^\d<2>\.\d<2>\.\d<4>$ «, message=»Datumseingabe nicht korrekt») private Date .
39. IllegalArgumentException when creating FixedLengthTokenizer forum.springsource.org
IllegalArgumentException when creating FixedLengthTokenizer I have a FixedLengthTokenizer for a FlatFileItemReader like so: Code:
40. Urgent Help Needed: java.lang.IllegalArgumentException: Cannot locate BeanDefinitionD forum.springsource.org
I am trying to implement an object that needs to be globalSession scoped (Portlet). When I add the following bean definition to my context I receive the following error: java.lang.IllegalArgumentException: Cannot .
41. IllegalArgumentException trying to run PetClinicClientServer forum.springsource.org
Jun 10th, 2008, 08:50 AM #1 dexter View Profile View Forum Posts Private Message Junior Member Join Date Jun 2008 Posts 3 IllegalArgumentException trying to run PetClinicClientServer Hi, I’m trying to .
42. IllegalArgumentException at WebSphereUowTransactionManager forum.springsource.org
Hi I am using Spring 2.5.5 and WAS v6.1 . I describe following configuration, Code: forum.springsource.org
java.lang.IllegalArgumentException: ExecutionId must not be null I upgraded to Spring Batch 1.1.0 and ran a test that throws a runtime exception in my item writer. I can’t see why this would .
44. java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] forum.springsource.org
java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] HI, I face the problem when try to use the fixed length flat file parser. THe error is Code: Caused by: java.lang.IllegalArgumentException: Cannot convert .
45. IllegalArgumentException: ServletContext must not be null forum.springsource.org
IllegalArgumentException: ServletContext must not be null I’m getting the following error if i use the spring form tag. Please help. I’m stuck with this forever error. Nested Exception is java.lang.IllegalArgumentException: ServletContext .
46. Side effect of loglevel: java.lang.IllegalArgumentException: step execution is expect forum.springsource.org
Side effect of loglevel: java.lang.IllegalArgumentException: step execution is expect Dear forum I experience an exceptional behavior with spring-batch-1.1.2-RELEASE. It’s hard for me to explain/understand the situation so i attached an eclipse .
47. HELP: java.lang.IllegalArgumentException does not support command class forum.springsource.org
HELP: java.lang.IllegalArgumentException does not support command class Hi,everyone: i’m studying spring controller and get the exception when i try to validate a SimpleFormController with XML based validator. the springweb-servlet.xml : forum.springsource.org
java.lang.IllegalArgumentException: bundle context should be set before refreshing th Hi, When I start my Web / OSGI project using Spring DM servlet on my OSGI server, I receive the following error .
49. Aspect code not working — IllegalArgumentException forum.springsource.org
Hi All, I am new to AOP so apologies if this is trivial — but have done a search and tried a few things out and unfortunately no success. I’m getting .
50. @RequestMapping java.lang.IllegalArgumentException forum.springsource.org
@RequestMapping java.lang.IllegalArgumentException When i try to replace a parameter of type Model(or ModelMap etc) with a scala class that simply extends the ModelMap class, an «java.lang.IllegalArgumentException: argument type mismatch» that is .
51. java.lang.IllegalArgumentException: Cannot subclass final class class $Proxy112 forum.springsource.org
java.lang.IllegalArgumentException: Cannot subclass final class class $Proxy112 When i am traying to use both the AOP logging and transaction (TransactionProxyFactoryBean) while deploing i am getting error an ‘forecastProcess’ while setting bean .
52. Error: IllegalArgumentException: Original must not be null forum.springsource.org
Error: IllegalArgumentException: Original must not be null Hi! My name is Bruno I am brasilian and I’ll try put my question here. (My english is not so good) Well, I am .
53. IllegalArgumentException: Cannot convert value of type [java.lang.String] to required forum.springsource.org
IllegalArgumentException: Cannot convert value of type [java.lang.String] to required I have a Date data type in form and when I try to input this dateChanged is of data type Date which .
54. IllegalArgumentException at FilterInvocationDefinitionSource forum.springsource.org
IllegalArgumentException at FilterInvocationDefinitionSource I am trying to figure out Spring filters. The first filter I added is httpSessionIntegrationFilter. Below is my entry the spring-config.xml file. I am getting an IllegalArgumentException when .
55. IllegalArgumentException: class is not an enhanced class forum.springsource.org
I`m trying to test Spring 3.0RC1 with jsf 1.2. I`m testing Glassfish v3 with OSGI and Equinox. When i deploing my webapp, Spring tries to create scoped proxy of one of .
56. IllegalArgumentException: error wildcard type pattern not allowed, must use type name forum.springsource.org
Please review the following code: Code: package com.simple.aspect.system; @Aspect public class SystemArchitectureAspect < @Pointcut(«witin(com.simple.web..*)») public void inWebLayer() <>@Pointcut(«within(com.simple.aspect..*)») public void inAspectLayer() <> @Pointcut(«execution(* com.simple..*.*(..)) && !inAspectLayer()») public void allOperations() <> .
57. IllegalArgumentException: Method must not be null forum.springsource.org
Feb 4th, 2010, 01:55 PM #1 Barbidure View Profile View Forum Posts Private Message Junior Member Join Date Nov 2009 Posts 6 IllegalArgumentException: Method must not be null Hello, I try .
58. IllegalArgumentException with ApplicationContextAware + Proxy forum.springsource.org
IllegalArgumentException with ApplicationContextAware + Proxy Hi All, I get an exception when implementing ApplicationContextAware when proxies are used. Without ApplicationContextAware it works. Without proxy it works too. It has been reproduced .
Источник
I have an abstract class which are implementing some basic interface.
(attack method is not inherited from basic interface)
public abstract class AbstractClass implements BasicInterface {
public void attack(String attackerId, float attackerAttackSpeed) {
... // method body
}
}
I have also an class which are extending abstract class.
@Service
public class A extends AbstractClass {
// other methods...
}
Right now im trying to observe method attack(String attackerId, float attackerSpeedAttack)
@Aspect
@Component
public class AspectJ{
@After(value = "execution(* package.A.attack(attackerId, ..)) && args(attackerId)")
public void broadcastAttackMessage(String attackerId) {
... //method body
}
}
But unfortunately Intellij told me that This advise advises to no methods.
Also during starting the application i received error with a stack trace :
Caused by: java.lang.IllegalArgumentException: error at ::0 name binding only allowed in target, this, and args pcds
What i’m doing wrong? Is there any way to observe method from super class? Do i miss something?
Previous related articles:
AOP core concepts and aspects of SpringAOP
10 minutes introduction to SpringAOP
The introduction
What is the PCD
PCD(pointcut designators) is SpringAOP’s pointcut expressions. SpringAOP’s PCD is fully aspectj-compatible, and there are 10 of them.
PCD general map
Use guide
SpringAOP is based on dynamic proxy implementation, where proxied beans are represented as target objects, and proxy objects represent beans built by AOP. The target method represents the proxied method.
execution
Execution is the most commonly used PCD. Its matching template is shown below:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)
throws-pattern?) Execution? Return type match class name match? Method name matching (parameter matching) exception matching?Copy the code
Code block with? The matching of symbols is optional, with only three essential to execution:
- Return value Matches the value
- Method name matching formula
- Parameter matching formula
Execution (public * ServiceDemo.*(..)) ServiceDemo = public; ServiceDemo = public; ServiceDemo = public; ServiceDemo = public; Is the parameter matching formula, matching any number, any type of parameter method.
Here are some other examples:
-
execution(* com.xyz.service.. *. * (..) ): matches any method under com.xyz.service and its subpackages.
-
Execution (* Joke (Object+)) : Matches any method named Joke whose dynamic entry is of type Object or a subclass of that class.
-
execution(* joke(String,..) ): matches any method named Joke, which has an input parameter of String(not subclass) and can be followed by any input parameter of any type
-
execution(* com.. *.*Dao.find*(..) ): matches methods that start with find under the specified package
-
execution(* com.baobaotao.Waiter+.*(..) ) : matches all methods of Waiter and its subclasses under the com.baobaotao package.
within
Filter all classes in a package with *.
-
Class within(com.xyz.service.*)com.xyz.service package, excluding subpackages
-
within(com.xyz.service.. *) classes under com.xyz.service and its subpackages
this
This is often used to name binding patterns. Filter by type of proxy object.
If the target class is implemented based on an interface, this() can be filled with the full path name of the interface; otherwise, because the target class is implemented based on CGLIB, this can be filled with the full path name of the target class.
This (com) xyz) service. AccountService) : the proxy class is com. Xyz service. AccountService or its subclasses.
CGLIB can be enforced using @enableAspectJAutoProxy (proxyTargetClass = true). Otherwise, the JDK dynamic proxy will be used first by default, and CGLIB will be used only if the JDK proxy cannot be used.
target
This applies to the proxy object and target to the target object.
Target (com) xyz) service. AccountService) : is the proxy class (target) is com. Xyz. Service. AccountService or its subclasses
args
Often used to match the parameters of a target method. Generally not used alone, but in conjunction with other PCDS to use. Args can use named binding mode, as shown in the following example:
@Aspect // Section declaration
@Component / / into the IOC
@Slf4j
class AspectDemo {
@Around("within(per.aop.*) args(str)")
- If arGS is
Parameter names
, along with the use of the advice method to determine the type of method parameter to match. - If args is a type, for example
@ Around (" within (per. Aop. *) args (String) ")
, you don’t need to use the section method to determine the type, but you can’t use parameter binding at this point eitherSee below.
Although ARgs () supports the + symbol, the provincial ARgs () supports subclass wildcards.
And strip parameters matchexecution
The difference between
For example: args(com.xgj.waiter) is equivalent to execution(* *(com.xgj.waiter +)). And execution does not support advice with parameters.
@target
Scenario Example: If a Service has multiple subclasses and some subclasses need to log and some subclasses do not need to log, you can perform the following operations (combined with Java polymorphism):
Filter out that the proxied object with the given annotation is an object, not a class, and @target is dynamic. Define a custom annotation LogAble as follows:
// Fully qualified name: annotation.logable
@Target({ElementType.TYPE,ElementType.PARAMETER}) // Support annotation on method parameters and classes
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAble {
}
Copy the code
If you need to log all public methods of the class annotated with this annotation, the logging logic needs to be customized. You can write PCD as follows, and of course the corresponding method bean needs to be injected into the SpringIOC container:
@Around("@target(annotation.LogAble) execution(public * *.*(..) )"
// Customize log logic
Copy the code
@args
Annotation @args specifies the runtime type of the target method parameter. The type of the method parameter is annotated, not the method parameter.
Usage scenario: If the parameter type has more than one subclass, only one subclass can match the PCD.
-
@ the args (com. Ms. Aop. Jargs. Not. Anno1) : match a parameter, and the first parameter runtime requires Anno1 annotation
-
@args(com.ms.aop.jargs.demo1.Anno1,..) Matches one or more arguments, the first of which should be annotated Anno1 at run time.
-
@ the args (com. Ms. Aop. Jargs. Not. Anno1, com. Ms. Aop) jargs. Not the Anno2) : a matching Anno1, two matching Annno2 refs.
@within
@target of a non-runtime type. @target looks at the object being called, @within looks at the class of the method being called.
Differences between @target and @within:
@target(annotation A) : Determines whether annotation A is declared in the target object being called. If so, annotation A will be intercepted
@within: Determines whether annotation A is declared in the class to which the method is being called. If so, annotation A will be intercepted
@annotation
Matches methods with specified annotations (annotations apply to methods)
bean
Match by beanNam. * wildcard characters are supported.
bean(*Service) // Matches all services at the end of Service
Copy the code
other
Use a combination of
Support between PCD, | |! Three operators. The operator is used in the example above. | | said (not short circuit or). ! Say not.
Named binding mode
The @around («within(per.aop.*) args (STR)») example above uses the named binding pattern, writing the variable name in PCD and qualifying the type of the variable name in the method.
@Around("within(per.aop.*) args(str)")
public Object logAspect(ProceedingJoinPoint pjp, String str) { ...}
Copy the code
For example, if STR is a String or a subclass of it, and a method can have only one input parameter.
name binding only allowed in target, this, and args pcds
The named binding mode supports only target, this, and ARgs PCDS.
argNames
Looking at the source code, you can see that all Advice annotations have an argNames field, such as @around:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Around {
String value(a);
String argNames(a) default "";
}
Copy the code
When this attribute is used, here is an example:
@Around(value = "execution(* TestBean.paramArgs(..) ) args(decimal,str,..) target(bean)", argNames = "pjp,str,decimal,bean")
@SneakyThrows // proceed will throw a test exception
Object aroundArgs(ProceedingJoinPoint pjp,
Argnames must be used with the args, target, and this tags. Although this parameter is optional in practice, it is recommended that all parameters be configured for the following reasons:
So if the ‘argerNames’ attribute is not specified, Spring AOP will look at the class’s debugging information and try to determine the parameter name from the local variation table. This information appears whenever the class is compiled using debugging information (at least ‘-g: Vars’). The result of compiling with this flag is:
(1) Your code will be more easily reverse-engineered)
(2) The class file size will be very large (usually insignificant)
(3) Optimizations that remove unused local variables will not be applied by the compiler.
In addition, if the compiled code does not have the necessary debugging information, Spring AOP will attempt to infer the pairing of binding variables and parameters. If the variable bindings under the available information is not clear, so a AmbiguousBindingException will be thrown. If all of the above strategies fail, an IllegalArgumentException is thrown.
It is recommended that all advice annotations include argNames as IDEA will remind you anyway.
Refer to the article
- Spring document
- SpringAOP Point expression
Связанные статьи в прошлом:
AOP Core Concept и Springaop Cut Surface
10 минут, чтобы начать Springaop
Статьи Справочник
- предисловие
-
- Что такое PCD
- Карта списка PCD
- руководство пользователя
-
- execution
- within
- this
- target
- args
-
- Отличается от соответствия параметров `execution ‘
- @target
- @args
- @within
- @annotation
- bean
- Другой
-
- Использовать
- Режим привязки именования
- argNames
- Справочная статья
предисловие
Что такое PCD
PCD (PointCut Disementals) является выражением точки выреза SpringAOOP. PCD Springaop полностью совместим с AspectJ, в общей сложности 10 видов.
Карта списка PCD
руководство пользователя
SpringAOP реализован на основе динамического прокси.цель
Указывает действующий боб, а прокси -объект представляет фасоль, построенный AOP. Целевой метод представляет метод представленного.
execution
Выполнение является наиболее часто используемым PCD. Его соответствующие шаблоны отображаются ниже:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)
throws-pattern?)
execution(Сопоставление модификатора? СООТВЕТСТВЕННОЕ тип типа сопоставление имени типа? Сопоставление имени метода(Сопоставление параметров) Аномальный?)
Кодовая блочная полоса?
Символы необязательны, дляexecution PCD
Есть только три предмета первой необходимости:
- Значение соответствующего значения возврата
- Сопоставление имени метода
- Сопоставление параметров
Пример анализа:execution(public * ServiceDemo.*(..))
Соответствует общественному модификатору, возвращаемое значение*
, То есть любой тип возвращаемого значения,ServiceDemo
Это классический матчНе нужно иметь полный путь, пока глобальная видимость является единственной.,.*
Это сопоставление имени метода, соответствующая всем методам,..
Это метод сопоставления параметров, который соответствует любому числу и любому типу параметра.
Возьмите несколько других примеров:
-
execution(* com.xyz.service..*.*(..))
: Сопоставление любых методов в соответствии с com.xyz.service и его сыном. -
execution(* joke(Object+)))
: Сопоставление любого имениjoke
Метод динамических параметров является типом объекта или подклассом этого класса. -
execution(* joke(String,..))
: Сопоставление любого имениjoke
Метод этого метода является строгим (не подклассом), и могут быть какие -либо параметры сзади. -
execution(* com..*.*Dao.find*(..))
: Сопоставление метода поиска, запускающегося в указанном пакете -
execution(* com.baobaotao.Waiter+.*(..))
: Соответствие пакета com.baobaotaoWaiter
И все методы их подклассов.
within
Экспроверьте все классы в сумке, обратите внимание на то, чтобы принести*
。
-
within(com.xyz.service.*)
Com.xyz.service Package в категории, за исключением подпадений -
within(com.xyz.service..*)
Com.xyz.service Package под и под его подплатой
this
Обычно используетсяРежим привязки именования
Сущность Фильтр и экран для типа объекта агента.
Если целевой класс реализован на основе интерфейса, тоthis()
Средняя часть может быть заполненаЭтот интерфейс
Вся название дороги, в противном случаеНЕ -Минтерфейс РеализацияПоскольку он реализован на основе cglib, он может быть заполнен в этомЦелевой класс
Все название пути.
this(com.xyz.service.AccountService)
: Прокси -класс -это com.xyz.service.accountservice или его суб -класс.
использовать@EnableAspectJAutoProxy(proxyTargetClass = true)
Cglib может быть вынужден использовать. В противном случае динамический прокси JDK используется по умолчанию, а прокси JDK не будет использоваться для использования CGLIB.
target
Это действует на прокси -объект, и цель действует на целевой объект.
target(com.xyz.service.AccountService)
: Acting Class (Target) -это com.xyz.service.accountservice или его суб -категория
args
Обычно используется для сопоставления параметров целевых методов. Как правило, не используйте его в одиночку, но используйте его с другими PCDS. ARG можно использоватьПривязка именования
Модель, например:
@Aspect // Отрежьте утверждение поверхности
@Component // инъекция IOC
@Slf4j
class AspectDemo {
@Around("within(per.aop.*) && args(str)") // под per.aop есть только один параметр, который является прокси. Тип параметра - строка или его подкласс
@SneakyThrows
public Object logAspect(ProceedingJoinPoint pjp, String str) {
String signature = pjp.getSignature().toString();
log.info("{} start,param={}", signature, pjp.getArgs());
Object res = pjp.proceed();
log.info("{} end", signature);
return res;
}
}
- Если это в арга
имя параметра
Использование метода консультаций для определения типа параметра метода, который будет сопоставлен. - Например, если есть тип в ARG
@Around("within(per.aop.*) && args(String)”)
Вы можете использовать метод резки для определения типа, но в настоящее время вы не можете использовать параметры, чтобы быть связанными.следующим образомЭто верно.
Несмотря на то чтоargs()
поддерживать+
Символ, но провинцияargs()
Поддержка суб -класса распределения.
Совпадать с параметрамиexecution
различия
Например: args(com.xgj.Waiter)
Эквивалентноexecution(* *(com.xgj.Waiter+))
Сущность И выполнение не может поддерживать консультации с параметрами.
@target
Пример: когда у сервиса есть несколько подклассов, некоторые подклассы должны воспроизводить журналы. Некоторые подклассы можно рассматривать следующим образом, когда им не нужно играть в журналы (с полиморфизмом Java):
Проверьте прокси -объект данным раствором впрыскаЭто объект, а не класс,@Target динамичнаСущность Следующим образом, настройте аннотациюLogAble
:
// полное ограниченное имя: аннотация.logable
@Target({ElementType.TYPE,ElementType.PARAMETER}) // Поддерживать параметры метода, классы в классе, примечание
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAble {
}
Если вам нужно «заметить» все классы этой аннотацииpublic
Метод «оба журнала журналаЛогика журнала должна быть настроенаВы можете написать PCD следующим образом. Конечно, соответствующий метод вводится в контейнер Springioc:
@Around("@target(annotation.LogAble) && execution(public * *.*(..))")
// пользовательская логика логики
@args
Для параметров целевого методаБежать
Должен@args
Укажите аннотацию. Существуют указанные аннотации в типе параметра метода, а не аннотацию параметра метода.
Используйте сцену: если тип параметра имеет несколько подклассов, только подкласс может соответствовать PCD.
-
@args(com.ms.aop.jargs.demo1.Anno1)
: Сопоставьте 1 параметр, и первый параметр должен иметь аннотацию Anno1 -
@args(com.ms.aop.jargs.demo1.Anno1,..)
Сопоставление одного или нескольких параметров, первый параметр должен принести аннотацию Anno1. -
@args(com.ms.aop.jargs.demo1.Anno1,com.ms.aop.jargs.demo1.Anno2)
: Один женьшень, соответствующий Anno1, два женьшеня, соответствующие Annno2.
@within
НетВремя выполнения
из@target
Сущность @Target обращает внимание на объект вызванного,@Intours Carese о классе, в котором находится метод вызова.
Различия между @Target и @Within:
@Target (Примечание A): Определите вызовцель
Объявлять аннотацию А, если да, это будет перехвачено
@within (примечание a): метод оценки метода вызванногоДобрый
Объявлять аннотацию А, если да, это будет перехвачено
@annotation
Сопоставление метода указанных аннотаций (эффект аннотации на методе)
bean
Матч согласно Beannam. поддерживать*
Проходить.
bean(*Service) // Сопоставление службы, заканчивающегося в конце сервиса
Другой
Использовать
Поддержка PCD,&& || !
Три оператора. Оператор && был использован в примере выше.||
Покажите (не короткий -циркуйт или).!
Выражать.
Режим привязки именования
Выше@Around("within(per.aop.*) && args(str)")
Примером является использование режима привязки именования, записать имя переменной в PCD и ограничить тип имени переменной в методе.
@Around("within(per.aop.*) && args(str)")
public Object logAspect(ProceedingJoinPoint pjp, String str) { ...}
Например, если STR является типом строки или его суб -класса, в методе есть только один метод.
name binding only allowed in target, this, and args pcds
Режим привязки именования поддерживает толькоtarget、this、args
Три ПКД.
argNames
Соблюдайте исходный код, вы можете обнаружить, что все консультацииargNames
Поля, такие как @Around:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Around {
String value();
String argNames() default "";
}
При каких обстоятельствах будет использоваться этот атрибут, объясняется следующий пример:
@Around(value = "execution(* TestBean.paramArgs(..)) && args(decimal,str,..)&& target(bean)", argNames = "pjp,str,decimal,bean")
@SneakyThrows // Продолжение проведет аномальную проверку
Object aroundArgs(ProceedingJoinPoint pjp,/*Используйте режим привязки именования*/ String str, BigDecimal decimal, Object bean) {
// выполняйте некоторые операции перед выполнением метода
return pjp.proceed();
}
Аргнамы должны использоваться с ARGS, Target и этими тегами. Хотя это не может быть внесено в фактическую работу, чиновник предполагает, что все параметры приводятся, причина заключается в следующем:
Следовательно, если атрибут «ArgerNames» не указан, то Spring AOP будет просмотреть информацию отладки класса и попытаться определить имя параметра из таблицы локальной переменной. Пока информация отладки (по крайней мере, «-G: vars») компилирует класс, появится эта информация. Результатом компиляции с использованием этого логотипа является:
(1) Ваш код будет проще быть в обратном проекте)
(2) Размер файла класса будет очень большим (обычно не имеет значения)
(3) Оптимизация удаления неиспользованных локальных переменных не будет применена компиляторами.
Кроме того, если скомпилированный код не нуждается в отладке информации, то Spring AOP попытается сделать вывод о сочетании переменных и параметров привязки. Если привязка переменной не ясна при доступной информации, то будет выброшено неоднозначное обоснование. Если вышеупомянутые стратегии терпят неудачу, то будет брошено нелегаларгументация.
Рекомендуется привести все консультации
argNames
Во всяком случае, идея также напоминает.
Справочная статья
- Весенняя документация
- Springaop Point Expression