Compare commits

...

247 Commits

Author SHA1 Message Date
Spring Buildmaster 4397bb07d8 Release version 5.0.8.RELEASE 2018-07-26 07:49:26 +00:00
Juergen Hoeller d7cf2c869c MethodBeforeAdviceInterceptor implements BeforeAdvice marker interface
Includes related polishing in the advice interceptor implementations.

Issue: SPR-17088

(cherry picked from commit 4e03d3fdcb)
2018-07-25 20:16:48 +02:00
Juergen Hoeller c89fb745f7 ListBasedXMLEventReader uses defensive modifiable copy of given List
(cherry picked from commit 9ab63b8494)
2018-07-25 19:06:55 +02:00
Juergen Hoeller e214ee5c85 Backport of WebMvcConfigurationSupport javadoc revision 2018-07-25 15:39:39 +02:00
Juergen Hoeller 93ef169c5c Polishing 2018-07-25 14:40:31 +02:00
Brian Clozel 407bd96cf3 ResponseEntityResultHandler overwrites headers
Prior to this commit, controller handlers (regular and exception
handlers as well) would not overwrite existing HTTP response headers on
the exchange. This would lead to situations where Content-Type values
set during the initial handling phase would not be overwritten when
handling an error later on.

This commit aligns the implementation of that result handler on the
Spring MVC one in that regard.

Issue: SPR-17082
(Cherry-picked from 195f3f07e7)
2018-07-24 22:23:52 +02:00
Juergen Hoeller 0b5c099de2 Polishing 2018-07-24 22:10:07 +02:00
Juergen Hoeller 4f9a18f5aa Order setter for DefaultSimpUserRegistry
Issue: SPR-17023
2018-07-24 18:56:52 +02:00
Rossen Stoyanchev 9b3d80c5e4 Update STOMP section on working with subscriptions
1. Revise @SubscribeMapping to address common points of confusion.
2. Add ExecutorSubsribableChannel.
3. Split Events and Interception in two.

Issue: SPR-16950
2018-07-24 12:25:41 -04:00
Rossen Stoyanchev dc066b0530 "Order of messages" in STOMP section of reference docs
Issue: SPR-13989
2018-07-24 12:23:39 -04:00
Juergen Hoeller 0c44b5224f Polishing
(cherry picked from commit dd4468a)
2018-07-24 16:34:56 +02:00
Juergen Hoeller 207e8c2409 BeanFactoryAdvisorRetrievalHelper avoids synchronization for name cache
Issue: SPR-16570

(cherry picked from commit 7f1a8d7)
2018-07-24 16:34:50 +02:00
Juergen Hoeller 2329588856 Upgrade to Mockito 2.19.1 2018-07-24 15:00:47 +02:00
Juergen Hoeller f677d684e7 Polishing 2018-07-24 15:00:35 +02:00
Juergen Hoeller 3878db2e8c Provide predetermined capacity for cache operation collections
Issue: SPR-17079

(cherry picked from commit 20c34cb)
2018-07-24 14:59:05 +02:00
Rossen Stoyanchev 24a113fb27 Ensure headers work with ResponseEntity + reactive body
Issue: SPR-17076
2018-07-24 00:26:01 -04:00
Juergen Hoeller e21db2619b AspectJExpressionPointcut leniently ignores non-composable interfaces
Issue: SPR-17003

(cherry picked from commit bccff73)
2018-07-22 22:35:32 +02:00
Juergen Hoeller f5dd4d2c02 Polishing 2018-07-22 19:33:40 +02:00
Juergen Hoeller 192113de60 Correctly determine and propagate validation hints to DataBinder
Issue: SPR-17073

(cherry picked from commit 3c65c17)
2018-07-21 12:34:55 +02:00
Brian Clozel f89511e7fe Switch order of multipart Content-Type directives
Since SPR-15205, the `FormHttpMessageConverter` is adding a `charset`
directive to the `Content-Type` request header in order to help servers
understand which charset is being used to encode headers of each part.

As reported in SPR-17030 and others, some servers are not parsing
properly such header values and assume that `boundary` is the last
directive in the `Content-Type` header.

This commit reorders the charset information right before the boundary
declaration to get around those issues.

Issue: SPR-17030
(Cherry-picked from 390bb871d8)
2018-07-20 18:16:53 +02:00
Juergen Hoeller c3f6403f61 Polishing 2018-07-20 16:45:17 +02:00
Rossen Stoyanchev 5007d01c17 Fix for encoding issue with MvcUriComponentsBuilder
Provide method for stronger encoding of expanded URI variables when
building links from views.

Issue: SPR-17027
2018-07-19 19:07:22 -04:00
Rossen Stoyanchev f1c55a3b4a UriComponentsBuilder method to configure URI variables
See Javadoc on UriComponentsBuilder#uriVariables for details.

This helps to prepare for SPR-17027 where the MvcUriComponentsBuilder
already does a partial expand but was forced to build UriComonents
and then create a new UriComponentsBuilder from it to continue. This
change makes it possible to stay with the same builder instance.

Issue: SPR-17027
2018-07-19 19:07:22 -04:00
Rossen Stoyanchev 34a0cdfc33 Minor fixes: UriComponentsBuilder, UriComponents, docs
After the latest changes, two small fixes in the clone method to copy
the encode flag, and in the encodeUriTemplate method to account for
possible null query params.

Improvements in the URI encoding section.

Issue: SPR-17039, SPR-17027
2018-07-19 19:07:22 -04:00
Juergen Hoeller 1cd0135195 Restore original DefaultAdvisorChainFactory MethodMatcher invocation
Includes test for @Async pointcut against AOP proxy without target.
2018-07-20 00:33:27 +02:00
Juergen Hoeller 0c5c3103c6 ReflectiveMethodExecutor skips interface search (plus related polishing) 2018-07-19 16:51:13 +02:00
Juergen Hoeller c66f9d8880 Javadoc update: ConfigurationClassPostProcessor is priority-ordered
Issue: SPR-17062

(cherry picked from commit 0b60447)
2018-07-19 13:24:48 +02:00
Juergen Hoeller 4d3a899a53 OrderUtils caches order values (for AnnotationAwareOrderComparator)
Issue: SPR-17064

(cherry picked from commit d0bbbf4)
2018-07-19 13:24:43 +02:00
Juergen Hoeller 11fc086309 Prefer ArrayList/ArrayDeque over LinkedList for multi-element holders
LinkedList remains in place where a List is likely to remain empty or single-element (in order to avoid unused capacity).

Issue: SPR-17037

(cherry picked from commit 9c08a48)
2018-07-19 00:08:13 +02:00
Juergen Hoeller ed54895e53 Consistent exposure of nested parameter type in binding exceptions 2018-07-18 19:56:06 +02:00
Juergen Hoeller b72594d799 Find annotations on implemented generic interface methods as well
Issue: SPR-16060

(cherry picked from commit 23d4862)
2018-07-18 19:56:00 +02:00
Juergen Hoeller 4341838a21 Polishing 2018-07-18 14:53:19 +02:00
Brian Clozel 58f58e404e Avoid null signals when resolving handler arguments
Prior to this commit, resolving an argument for a WebFlux controller
that's missing from the request and not required by the handler would
throw a NullPointerException in some cases.

This involves the conversion of the parameter (a `String` parameter type
might not trigger this behavior) and sending a `null` within a reactive
stream, which is illegal per the RS spec.

We now rely on a `Mono.justOrEmpty()` to handle those specific cases.

Issue: SPR-17050
(Cherry-picked from a7f97a1669)
2018-07-18 14:48:06 +02:00
Juergen Hoeller c0040a5508 Polishing 2018-07-18 14:03:54 +02:00
Juergen Hoeller 55563c16b5 StringUtils.parseLocaleString detects variant without country
The parseLocale method also turns an empty locale into null now, compatible with parseLocaleString behavior.

Includes tests for parsing all available locales on the JVM, checking toString/toLanguageTag equality between parsed and original locale.

Issue: SPR-7598
Issue: SPR-16651

(cherry picked from commit cab35aa)
2018-07-18 14:03:30 +02:00
Juergen Hoeller ae1d500bc3 UrlBasedViewResolver exposes redirect prefix as bean name
Issue: SPR-17045

(cherry picked from commit b8d2a16)
2018-07-18 13:59:32 +02:00
Juergen Hoeller 9134588a82 Never return null from AnnotationMetadata.getMetaAnnotationTypes
Issue: SPR-17046

(cherry picked from commit cacd14c)
2018-07-18 13:59:11 +02:00
Juergen Hoeller d283424c82 Update ref doc references to Number/Currency/PercentStyleFormatter
Issue: SPR-17022

(cherry picked from commit 39d4550)
2018-07-18 13:58:45 +02:00
Andrew McCallum 6e019f9ed0 Correct method signature in code example
Closes gh-1887
2018-07-18 09:08:29 +02:00
Rossen Stoyanchev d9d41b4398 Polish 2018-07-17 17:41:44 -04:00
Rossen Stoyanchev eac0ddce13 Update URI Encoding section 2018-07-17 15:58:47 -04:00
Rossen Stoyanchev a363a229eb Update URI links section after encoding changes
Issue: SPR-17039
2018-07-16 21:25:27 -04:00
Rossen Stoyanchev 2bf7c18203 Add TEMPLATE_AND_VALUES mode to DefaultUriBuilderFactory
Issue: SPR-17039
2018-07-16 21:25:09 -04:00
Rossen Stoyanchev 9458186e83 Polish DefaultUriBuilderFactory 2018-07-16 21:24:52 -04:00
Rossen Stoyanchev d81ec55a60 Support for encode() in UriComponentsBuilder
The ability to request to encode before `build()`, and more importantly
before expanding, allows stricter encoding to be applied to URI vars
and consequently to neutralize the effect of characters with reserved
meaning in a URI.

Issue: SPR-17039
2018-07-16 21:24:16 -04:00
Stephane Nicoll 4c8d81bcb4 Fix typo
Issue: SPR-17042
2018-07-15 16:18:25 +02:00
Rossen Stoyanchev 6218db9831 Backport of InMemoryWebSession changes
- hooks to check expired sessions in both create and retrieve.
- maxSessions limit on the total number of sessions.
- getSessions method for management purposes
- removeExpiredSessions public API

Issue: SPR-17020, SPR-16713
2018-07-12 16:27:42 -04:00
Rossen Stoyanchev 7ea8ecb6ab Warn when SimpleAsyncTaskExecutor is used
Issue: SPR-16203
2018-07-11 11:21:49 -04:00
Guilherme Alan Ritter 8c1bc63c9d Fix typo
Closes gh-1880
2018-07-10 15:48:40 +02:00
Rossen Stoyanchev f179181b40 Polish Reactive Spring Web section 2018-07-09 15:58:35 -04:00
Juergen Hoeller eb3254d2a9 Polishing 2018-07-06 15:18:47 +02:00
Juergen Hoeller 6cae0650e6 Upgrade to Jackson 2.9.6 2018-07-06 01:42:07 +02:00
Juergen Hoeller 43868d2b72 Polishing 2018-07-06 01:39:34 +02:00
Juergen Hoeller a8b747c21c Polishing 2018-07-04 22:55:38 +02:00
Juergen Hoeller 490b78a3d3 Polishing 2018-07-04 20:58:27 +02:00
Juergen Hoeller 1ab9e2ceda Polishing 2018-07-04 15:46:52 +02:00
Juergen Hoeller a1d35c23aa ConcurrentModel.addAttribute javadoc: null value not supported
Issue: SPR-16831
2018-07-04 15:45:53 +02:00
Juergen Hoeller 99534a31ba MapSqlParameterSource.addValue declares nullable value parameter
Issue: SPR-16843

(cherry picked from commit d9c6318)
2018-07-04 15:45:32 +02:00
Sebastien Deleuze c6dbfe42d3 Upgrade to Kotlin 1.2.51 2018-07-04 11:25:01 +02:00
Juergen Hoeller acf9ea097a Polishing 2018-07-03 17:11:27 +02:00
Juergen Hoeller decbb43757 Upgrade to Apache Johnzon 1.1.8 2018-07-03 16:23:51 +02:00
Juergen Hoeller 0480e75785 Polishing 2018-07-03 16:23:43 +02:00
Juergen Hoeller ac1e2879e5 Consistent throwing of HttpMessageNotReadableException (5.0.x revision)
Includes specific fine-tuning of ProtobufHttpMessageConverter and JAXB2 based message converters, as well as revised javadoc for abstract base classes.

Issue: SPR-16995
2018-07-03 16:23:36 +02:00
Juergen Hoeller ce0323fa8c ConcurrentReferenceHashMap caches EntrySet in volatile field
Includes an efficient implementation of isEmpty(), not relying on a full entry count but rather backing out once a non-empty hash segment has been found.

Issue: SPR-16994
2018-07-03 16:23:28 +02:00
Juergen Hoeller 0052c899bd Same method filtering in ConstructorResolver and getTypeForFactoryMethod
Issue: SPR-16999

(cherry picked from commit f2787cf)
2018-07-03 16:23:20 +02:00
Juergen Hoeller 8c07c6d099 Polishing 2018-07-01 02:35:35 +02:00
Juergen Hoeller 214fa9c2a0 Polishing 2018-06-29 22:43:13 +02:00
Juergen Hoeller ea534b6820 Polishing 2018-06-29 20:07:53 +02:00
Juergen Hoeller 5a111125c1 Up-to-date coverage of task executor and scheduler variants
Includes a clarification of ThreadPoolExecutor configuration options and a note on early AsyncConfigurer initialization.

Issue: SPR-16944
Issue: SPR-16945

(cherry picked from commit d58c09b)
2018-06-29 20:07:44 +02:00
Juergen Hoeller ac48c64b1a Upgrade to Mockito 2.19 and Mockito Kotlin 1.6 2018-06-28 18:13:59 +02:00
Juergen Hoeller 9a20ec9284 Polishing 2018-06-28 18:13:40 +02:00
Juergen Hoeller 03beee7b68 Upgrade to Tomcat 8.5.32, RxJava 2.1.16, Selenium 3.13 2018-06-28 17:33:30 +02:00
Juergen Hoeller 4be6bcae74 Polishing 2018-06-28 17:30:55 +02:00
Juergen Hoeller 6d0f8bf145 Support for new JsonMappingException wording in Jackson 2.9
Issue: SPR-16947
2018-06-28 16:42:35 +02:00
Juergen Hoeller a631af80c1 Polishing
(cherry picked from commit 40efcc9)
2018-06-28 16:42:14 +02:00
Juergen Hoeller 3e64388b20 Conventions lazily retrieves shared ReactiveAdapterRegistry
Issue: SPR-16981

(cherry picked from commit b68e692)
2018-06-28 16:41:51 +02:00
Juergen Hoeller d3b06a15f2 StringUtils.cleanPath retains plain pointer to current directory
Issue: SPR-16908

(cherry picked from commit 7a02e43)
2018-06-28 16:41:44 +02:00
Juergen Hoeller 75f26eec98 Fix FreeMarker escaping regression for messages and separators
Issue: SPR-16951

(cherry picked from commit 08e1c8c)
2018-06-28 16:41:33 +02:00
Juergen Hoeller 4402336c44 MimeTypeUtils lazily initializes SecureRandom for multipart boundary
Issue: SPR-16974

(cherry picked from commit 847202c)
2018-06-28 16:41:18 +02:00
Juergen Hoeller e388ddfdde WebHttpHandlerBuilder retains ApplicationContext in copy constructor
Issue: SPR-16972

(cherry picked from commit 2a15962)
2018-06-28 16:41:13 +02:00
Napster f83a01e573 Undertow WebSocket sessions share ByteBufferPool
Issues: SPR-16957
2018-06-25 17:59:34 -03:00
Brian Clozel d1c9401dc2 WebClient writes Content-Length for Mono bodies
In SPR-16892, the `EncoderHttpMessageWriter` has been improved to write
`"Content-Length"` HTTP response headers if the response body is of type
`Mono` (i.e. the actual content length is easily accessible without
buffering a possibly large response body). That change was relying on
the fact that the server side is using a `ChannelSendOperator` to delay
the writing of the body until the first signal is received.

This strategy is not effective on the client side, since no such channel
operator is used for `WebClient`. This commit improves
`EncoderHttpMessageWriter` and delays, for `Mono` HTTP message bodies
only, the writing of the body so that we can write the
`"Content-Length"` header information once we've got the body resolved.

Issue: SPR-16949
(Cherry-picked from 4a26f93a0d)
2018-06-19 11:52:26 +02:00
Ryan Yin 60838dcd03 Fix broken link to CONTRIBUTING.md
Closes gh-1860
2018-06-19 09:08:13 +02:00
Rossen Stoyanchev 3526766635 Fix documentation issue 2018-06-18 20:35:57 -04:00
Rossen Stoyanchev 425c311d3c Correctly set maxAge and expires in ResponseCookie
Issue: SPR-16940
2018-06-14 13:16:55 -04:00
Rossen Stoyanchev 24acae1195 Polish ExchangeFilterFunction[s] 2018-06-13 17:15:47 -04:00
Rossen Stoyanchev 49f21ac3ac Polish form writer and converter 2018-06-13 17:15:36 -04:00
Rossen Stoyanchev 8339e7ade5 Use reflection for JdkFlowAdapter
To avoid compiler issues on Eclipse.
2018-06-13 09:41:10 -04:00
Spring Buildmaster 4560f096b9 Next Development Version 2018-06-12 15:09:58 +00:00
Rossen Stoyanchev 4ec9f5df5c Minor polishing for URI encoding docs 2018-06-12 10:15:43 -04:00
Juergen Hoeller 224fcc1712 Remove outdated Servlet environment constraints from annotation javadoc
Includes removal of PathVariable's MultiValueMap support claim.

Issue: SPR-16936

(cherry picked from commit 0b64bcd)
2018-06-12 11:35:55 +02:00
Brian Clozel 96eba8b997 Fix ResourceRegion HttpMessageConverter write checks
This commit fixes the write checks for
`ResourceRegionHttpMessageConverter`, which was previously not checking
properly the parameterized type (e.g. in case of a `List<Something>`).

Issue: SPR-16932
(Cherry-picked from 05ff8b722d)
2018-06-11 22:57:36 +02:00
Rossen Stoyanchev be5229949c Add HTTP caching to WebFlux section
Issue: SPR-16395
2018-06-11 16:44:35 -04:00
Rossen Stoyanchev 516937cfc5 Polish Spring MVC docs on HTTP Caching
Issue: SPR-16395
2018-06-11 16:44:25 -04:00
Brian Clozel dac97f1b7d Restrict HTTP methods on Reactive HiddenHttpMethodFilter
This commit restricts the allowed HTTP methods on HiddenHttpMethodFilter
(Reactive variant) to the following: PUT, DELETE, PATCH.

This filter is meant to be used to simulate those methods from HTML
forms sent by browsers, so no other methods are allowed.

Issue: SPR-16836
(Cherry-picked from a5cd01a4c8)
2018-06-11 19:17:00 +02:00
Brian Clozel f2694a8ed9 Restrict HTTP methods on Servlet HiddenHttpMethodFilter
This commit restricts the allowed HTTP methods on HiddenHttpMethodFilter
(Servlet variant) to the following: PUT, DELETE, PATCH.

This filter is meant to be used to simulate those methods from HTML
forms sent by browsers, so no other methods are allowed.

Issue: SPR-16836
(Cherry-picked from f64fa3dea1)
2018-06-11 19:16:44 +02:00
Juergen Hoeller 82f421bff8 Upgrade to Reactor Bismuth SR10 2018-06-11 18:09:01 +02:00
Juergen Hoeller a2765c009e Polishing 2018-06-11 18:08:39 +02:00
Juergen Hoeller 78d3164543 Remove outdated javadoc references to SpEL lambda functions
Issue: SPR-16930

(cherry picked from commit 6df7ba2)
2018-06-11 18:08:20 +02:00
Brian Clozel afcc430481 Remove dependency management noise from POMs
Prior to this commit, the generated POMs for Spring Framework modules
would contain unneeded/harmful information from the Spring Framework
build:

1. The BOM imports applied to each module by the dependency
management plugin, for example for Netty or Reactor Netty.
Spring should not export that opinion to its POMs.

2. The exclusion of "org.slf4:jcl-over-slf4j" from *all* dependencies,
which made the POMs much larger than necessary and suggested to
developers that they should exclude it as well when using all those
listed dependencies. In fact, only Apache Tiles currently brings that
transitively.

This commit removes that information from the POMs.
The dependencyManagement Gradle plugin is disabled for POM generation
and we manually resolve the dependency versions during the generation
phase.
The Gradle build is streamlined to exclude "org.slf4:jcl-over-slf4j"
only when necessary.

Issue: SPR-16893
(Cherry-picked from 417354da8a)
2018-06-11 16:02:11 +02:00
Juergen Hoeller 062a15fbd7 Latest applicable dependency updates (Jetty 9.4.11, Netty 4.1.25, Hibernate ORM 5.1.14, HSQLDB 2.4.1, Derby 10.14.2.0, HtmlUnit 2.31, Selenium 3.12) 2018-06-11 15:02:44 +02:00
Juergen Hoeller c04c8a2472 Polishing 2018-06-11 15:01:18 +02:00
Juergen Hoeller f39adcf865 AbstractMethodMessageHandler processes Error as MessageHandlingException
Issue: SPR-16912
2018-06-11 14:59:44 +02:00
Juergen Hoeller da049f480b ReflectivePropertyAccessor caches sorted methods per class
Issue: SPR-16882
2018-06-11 14:59:08 +02:00
Juergen Hoeller 455d8ac7b9 Correct code example for YamlProcessor.setDocumentMatchers
Issue: SPR-16849

(cherry picked from commit 7ece0e2)
2018-06-11 14:58:42 +02:00
Sebastien Deleuze b80c13b722 Deprecate JSONP and disable it by default in Jackson view
Issue: SPR-16798
2018-06-08 12:31:40 +02:00
Rossen Stoyanchev 7bfd683816 Eliminate the need for Encoder#getContentLength
Issue: SPR-16892
2018-06-04 16:01:48 -04:00
Jason Zhekov fe01e5114d Fix format typo in webmvc.adoc
Closes gh-1849
2018-06-04 20:56:55 +02:00
Stephane Nicoll b5595c3904 Fix faulty BeanPostProcessorChecker logs with @EnableCaching
Issue: SPR-16896
2018-06-04 15:01:57 +02:00
Violeta Georgieva 76678e9c6a Fix code examples for WebFlux functional endpoints
Closes gh-1844
2018-05-31 15:19:28 +02:00
Johnny Lim b3a34f8397 Polish doc
Closes gh-1843
2018-05-31 10:21:36 +02:00
Juergen Hoeller 79adffd214 Upgrade to Hibernate Validator 6.0.10, RxJava 2.1.14, Gson 2.8.5 2018-05-30 11:59:57 +02:00
Juergen Hoeller af0a82931e Polishing
(cherry picked from commit 1b728fb)
2018-05-30 11:59:30 +02:00
Juergen Hoeller bbe5124556 Polishing 2018-05-29 22:16:48 +02:00
Juergen Hoeller 5935b7aefe Doc: @EnableScheduling needs to be declared per application context
Issue: SPR-16852

(cherry picked from commit b39ce80)
2018-05-29 22:00:34 +02:00
Juergen Hoeller a2d7cc7a69 AbstractRequestLoggingFilter.isIncludeHeaders() declared as protected
Issue: SPR-16881

(cherry picked from commit c754232)
2018-05-29 22:00:24 +02:00
Juergen Hoeller 8a56db6e4e SimpleAliasRegistry logs info message for alias overriding
Issue: SPR-16871

(cherry picked from commit 74fcdea)
2018-05-29 22:00:14 +02:00
Juergen Hoeller 50d6d90ed8 Restore lenient null return value for ConditionContext.getBeanFactory()
Includes nullable return value for getClassLoader() with corresponding notes in applicable javadoc.

Issue: SPR-16866

(cherry picked from commit 46a89d9)
2018-05-29 22:00:05 +02:00
Arjen Poutsma a7ffe092ab Fix parent path variables in nested route functions
This commit fix an issue where path variables in a nested parent
RouterFunction were not committed to the request attributes.

Issue: SPR-16868

(cherry picked from commit 8c30b8e)
2018-05-29 15:57:52 +02:00
Sebastien Deleuze 6407cb9baf Fix PropertyResolverExtensions.kt location 2018-05-28 15:53:03 +02:00
Gary Russell 0bc0762577 Fix JMS Doc typo
There is no such class `ReplyQosSettings`.

Closes gh-1836
2018-05-25 16:32:09 +02:00
Rossen Stoyanchev 051ab05d32 Properly initialize URI/Matrix vars w/ urlDecode=false
Issue: SPR-16867
2018-05-24 15:10:55 -04:00
Rossen Stoyanchev 9d36fd0b68 Respect async request timeout of -1 in MockMvc
When falling back on the timeout associated with the async request,
a value of -1 must be treated as: never time out.

Issue: SPR-16869
2018-05-24 12:36:47 -04:00
Rossen Stoyanchev f078e057ce Update docs on WebClient filters 2018-05-24 07:20:24 -04:00
Rossen Stoyanchev 941186a359 Minor update to STOMP chapter
Issue: SPR-16681
2018-05-23 21:50:46 -04:00
Rossen Stoyanchev 27fc4d6053 ChannelInterceptor default methods + deprecate adapter 2018-05-23 21:50:34 -04:00
Rossen Stoyanchev 1943a1f5bd Fix error in WebFlux chapter on static resources
Issue: SPR-16864
2018-05-23 21:25:26 -04:00
Rossen Stoyanchev a158ff4c3d Return SslInfo only if X509Certificate[] present
Issue: SPR-16842
2018-05-23 14:58:23 -04:00
Rossen Stoyanchev a71bd7c03f Immutable Resource[Resolver|Transformer]Chains
Backport of #f121aa5e31, applied to spring-webflux only.

Issue: SPR-16862
2018-05-23 09:53:26 -04:00
Sebastien Deleuze 1fefe2ab0c Upgrade to Dokka 0.9.17 2018-05-22 17:44:28 +02:00
Rossen Stoyanchev 0b36c9437e CodecConfigurer internal refactoring
Improve how HTTP message writers are obtained for general use vs for
multipart requests.
2018-05-21 21:15:17 -04:00
Rossen Stoyanchev 72e7687b80 Polish CodecConfigurer related classes
Functionally equivalent updates to package private classes to improve
the code and make it easier to understand.
2018-05-21 21:15:05 -04:00
Rossen Stoyanchev e87355b29c STOMP client supports setting accept-version
Issue: SPR-16844
2018-05-18 15:13:14 -04:00
Rossen Stoyanchev 1dc8201df1 Polish ReactiveAdapterRegisry 2018-05-18 09:30:10 -04:00
Rossen Stoyanchev e3e975d7f9 Support for SslInfo in ServerHttpRequest#mutate
Issue: SPR-16830
2018-05-17 17:29:33 -04:00
Rossen Stoyanchev b385ff1d9f Polish WebFlux WebSocket docs
Issue: SPR-16820
2018-05-17 10:03:24 -04:00
Arjen Poutsma 3c88029dd3 Improve toString for filtered router function
Issue: SPR-16829

(cherry picked from commit f722f40)
2018-05-17 12:02:57 +02:00
Rossen Stoyanchev c7adf28f61 Expand WebFlux docs with WebSocketHandler examples
Issue: SPR-16820
2018-05-16 21:33:47 -04:00
Rossen Stoyanchev c555fef6f2 Improve TCP connection info logging.
After the recent changes to expose configuring TcpOperations, it no
longer makes sense to automatically log the relayHost/Port since that's
mutually exclusive with a custom TcpOperations.

Instead we delegate to TcpOperations.toString().

Issue: SPR-16801
2018-05-16 14:26:29 -04:00
Rossen Stoyanchev ab0b0b31fd Polish: simplify ControllerMethodResolver initialization 2018-05-16 10:04:08 -04:00
Arjen Poutsma d24546ad18 Improve toString for query param and path extension predicates
Issue: SPR-16829

(cherry picked from commit 7424ca5)
2018-05-16 11:16:11 +02:00
Juergen Hoeller 2818051aff Revised code examples for stored procedure type declarations
Issue: SPR-16811

(cherry picked from commit 765d18e)
2018-05-16 09:09:55 +02:00
Juergen Hoeller a3bcdbe371 SchedulerFactoryBean triggers shutdown after registration failure
Issue: SPR-16816

(cherry picked from commit 0098245)
2018-05-16 09:09:44 +02:00
Juergen Hoeller 3978d5500d Query termination for JPA 2.1 StoredProcedureQuery.execute() method
Issue: SPR-16826

(cherry picked from commit 3c8c996)
2018-05-16 09:09:35 +02:00
Juergen Hoeller 416dee7226 AspectJExpressionPointcut evaluates interface method on proxy as well
Issue: SPR-16803

(cherry picked from commit bba5dca)
2018-05-16 09:09:24 +02:00
Sebastien Deleuze 4d69ec48b1 Add StatusResultMatchers.isEqualTo Kotlin extension
Issue: SPR-16429
2018-05-15 15:42:25 +02:00
Sebastien Deleuze 14a9d291e1 Filter synthetic in ReflectionUtils#USER_DECLARED_METHODS
Issue: SPR-16823
2018-05-15 15:01:31 +02:00
Sebastien Deleuze 5183f71a78 Update Kotlin refdoc with the new tutorial 2018-05-14 10:54:10 +02:00
Rossen Stoyanchev fd36af6fcf Inject UriComponentsBuilder relative to webapp root
Issue: SPR-16813
2018-05-11 09:54:35 -04:00
Rossen Stoyanchev 9179a4fa30 Correct coordinates for Reactor Netty in STOMP chapter
Issue: SPR-16802
2018-05-10 16:47:17 -04:00
nkjackzhang 98335b41f7 Fix a typo in javadoc
Closes gh-1824
2018-05-10 17:32:58 +02:00
Rossen Stoyanchev e9f4dec08c Restore layout of docs zip with index.html at the top
Issue: SPR-16799
2018-05-09 17:29:38 -04:00
Spring Buildmaster 4ec695b4d9 Next Development Version 2018-05-08 08:34:28 +00:00
Juergen Hoeller 2da02ccbd0 Polishing
(cherry picked from commit 70424a7)
2018-05-08 00:25:46 +02:00
Juergen Hoeller f2cc70ecf9 Explicit coverage of root vs cause exception matching in MVC ref docs
Issue: SPR-16743

(cherry picked from commit a200df6)
2018-05-07 23:18:33 +02:00
Rossen Stoyanchev e2115594c0 Document throwExceptionIfNoHandlerFound property
Issue: SPR-16786
2018-05-07 16:12:25 -04:00
Juergen Hoeller 2008e04354 Upgrade to Servlet API 4.0.1 2018-05-07 14:38:16 +02:00
Juergen Hoeller b4f83dbdc3 Polishing 2018-05-07 14:30:50 +02:00
Juergen Hoeller 0795ae5c6a Polishing 2018-05-05 16:55:06 +02:00
Juergen Hoeller 41ab177b6c Fine-tuned assertions and related polishing 2018-05-05 14:59:13 +02:00
Juergen Hoeller 8848ec73ab Refined backport of gh-1817 2018-05-05 13:18:08 +02:00
Juergen Hoeller 9f9481ec7b Upgrade to Tomcat 8.5.31, Undertow 1.4.25, Jetty 9.4.10, Gson 2.8.4
Includes upgrade from Reactor snapshots to Bismuth SR9.
2018-05-05 13:17:44 +02:00
Juergen Hoeller f6275e009b YamlProcessor embraces SnakeYAML 1.18+ duplicate key handling
Includes deprecation of StrictMapAppenderConstructor.

Issue: SPR-16791

(cherry picked from commit 138b0d0)
2018-05-05 13:17:10 +02:00
Juergen Hoeller ed44262a71 ResponseEntityExceptionHandler rethrows unknown exception (for further processing in DispatcherServlet's HandlerExceptionResolver chain)
Issue: SPR-16743

(cherry picked from commit 7b894fe)
2018-05-05 13:17:00 +02:00
Johnny Lim a0d37ac29e Remove inconsistent spaces
(cherry picked from commit fb898e1)
2018-05-05 12:49:26 +02:00
Johnny Lim a39938d251 Polish DatabaseStartupValidator
(cherry picked from commit 8f21cb1)
2018-05-05 12:49:10 +02:00
nkjackzhang edb33331ed Task "docsZip" copies duplicate reference files
Specify task "docsZip" source directory.
Issue: SPR-16789
2018-05-03 16:39:51 -04:00
Arjen Poutsma a63f04df09 Clean up path variables after non match
This commit makes sure the nested path variables are only commited to
the attributes when all predicates match.

Issue: SPR-16692

(cherry picked from commit 51325af)
2018-05-03 12:06:06 +02:00
Juergen Hoeller 5a98516f6c Lenient fallback to plain getBundle call without Control handle
Issue: SPR-16776
2018-05-02 16:54:38 +02:00
Juergen Hoeller 30363c84bd Consistent SpelEvaluationException messages in findAccessorForMethod
Issue: SPR-16762
2018-05-02 16:53:55 +02:00
Juergen Hoeller fa27130b82 Upgrade to RxJava 2.1.13, Hibernate ORM 5.2.17, AspectJ 1.9.1 2018-05-02 16:32:55 +02:00
Juergen Hoeller be4c07fc32 Expose FactoryBean's raw object on retrieval during post-processing
Issue: SPR-16783

(cherry picked from commit 9281f82)
2018-05-02 16:32:18 +02:00
Juergen Hoeller 22f421cc51 Introspect originating bean definition as configuration class candidate
Issue: SPR-16756

(cherry picked from commit c8b6233)
2018-05-02 16:31:57 +02:00
Juergen Hoeller 9dc538a7c6 Nullable HttpMethod parameter only on internal doExecute delegate
Issue: SPR-15540

(cherry picked from commit f8c2d7a)
2018-05-02 16:31:33 +02:00
Juergen Hoeller d74a2730ec SimpleClientHttpResponse catches any Exception on close
Issue: SPR-16773

(cherry picked from commit 21fad8e)
2018-05-02 16:07:22 +02:00
Juergen Hoeller 3e47f4564d Fine-tuned assertions and related polishing in WebFlux builders
(cherry picked from commit 9bff5b4)
2018-05-02 16:04:51 +02:00
Juergen Hoeller a9548f93e4 Support for non-standard HTTP status in reactive ClientHttpResponse
Issue: SPR-16748

(cherry picked from commit a683472)
2018-05-02 16:04:01 +02:00
Juergen Hoeller f2e77c292d Consistent target method resolution for event and caching expressions
Issue: SPR-16779

(cherry picked from commit eaff2c2)
2018-05-02 16:02:46 +02:00
Juergen Hoeller 8b051ab06e AopUtils.getMostSpecificMethod exposes dynamic proxy class methods
Includes efficient canApply check for IntroductionAwareMethodMatcher.

Issue: SPR-16757

(cherry picked from commit aa11721)
2018-05-02 16:01:48 +02:00
Oleksandr Hasheniuk 5a1d7f9c4b Improve performance of StringUtils#trimWhitespace
Issue: SPR-16766

(cherry picked from commit 6545cab)
2018-05-02 16:01:04 +02:00
Sebastien Deleuze b55f69deb1 Support decoding Mono in Jaxb2XmlDecoder
Issue: SPR-16759
2018-05-02 11:57:40 +02:00
Rossen Stoyanchev de1eb343e7 Polish WebSocketIntegrationTests 2018-05-01 14:26:44 -04:00
Rossen Stoyanchev 417bb302c3 ReactorNettyWebSocketSession implements close properly
Issue: SPR-16774
2018-05-01 12:05:20 -04:00
Rossen Stoyanchev b0aa08a671 Consistent handling of URISyntaxException
Issue: SPR-16778
2018-04-30 21:05:08 -04:00
Sebastien Deleuze 9dc79982e2 Upgrade to Kotlin 1.2.41
Fixes KT-23973 critical regression
2018-04-30 10:48:23 +02:00
Stephane Nicoll 43f2334e82 Keep YAML entries that haven an empty array value
Prior to this commit, a YAML entry that define an empty array value was
lost. This commit makes sure to flag it with an empty String, which
corresponds as an empty comma separated list of entries in the
properties format.

Issue: SPR-16769
2018-04-29 11:15:53 +02:00
Nickloas 6c6e44b58e Fix typo
Closes gh-1813
2018-04-28 10:52:03 +02:00
Johnny Lim c6b60f0c00 Polish 2018-04-27 14:09:35 -04:00
sdeleuze 7aba6ca9d6 Fine tune WebFlux server logging verbosity
With this commit, WebFlux server uses warning instead of error log level
for request handling, and also just print the message instead of the
stacktrace which is mostly meaningless in reactive world.

Complementary to this change, Reactor Netty removed additional logging
as part of https://github.com/reactor/reactor-netty/issues/339.

Issue: SPR-16688
2018-04-27 10:36:06 +02:00
nkjackzhang dca77c0666 Fix broken anchor link in WebFlux refdoc 2018-04-27 08:49:51 +02:00
sdeleuze df6e690e33 Reuse PartBodyStreamStorageFactory in SynchronossPartGenerator
Issue: SPR-16727
2018-04-26 11:01:17 +02:00
nkjackzhang a702ef8074 Fix typos in Spring MVC refdoc
1. Consistent with "xml code" examples.
2. "xml()" is a static method and will use default builder config,
   so use createXmlMapper(true) instead.
3. Fix mvc namespace tag typo.
2018-04-26 10:03:27 +02:00
Rossen Stoyanchev f7376bdde3 Better assertion message in MockPart
Issue: SPR-16767
2018-04-25 10:00:18 -04:00
nkjackzhang f9e31b503c Fix typos
Closes gh-1806
2018-04-25 10:07:34 +02:00
hasheniuk 3551dd92fb Fix typo
Closes gh-1804
2018-04-24 10:06:49 +02:00
Rossen Stoyanchev c23297fe76 Add more detail to ISE in ServerEndpointExporter
Issue: SPR-16655
2018-04-23 17:04:16 -04:00
Rossen Stoyanchev a5622d0dd2 Validate contextPath in RedirectView
Issue: SPR-16752
2018-04-23 15:21:33 -04:00
Brian Clozel 72cfe41f30 Disable HTTP Range support for InputStreamResource
Prior to this commit, the `AbstractMessageConverterMethodProcessor`
would fail to convert `InputStreamResource` to `ResourceRegion` as
expected, since the content length cannot be read without consuming the
stream. This is enforced by the `HttpRange` class.

Now the method processor would still try to output HTTP range response
headers to provide range support information. This step is using the
resource content length and reads the input stream, leading to
exceptions such as "IllegalStateException: InputStream has already been
read".

This commit improves the return type detection and excludes early
`InputStreamResource` return types. With those types, HTTP range support
is now completely disabled.

Issue: SPR-16754
(cherry picked from commit e9a8a5065b)
2018-04-23 18:40:15 +02:00
sdeleuze 4ff595e2bc Upgrade Kotlin to 1.2.40 2018-04-23 15:31:31 +02:00
sdeleuze 2c766b9501 Enable KotlinScriptTemplateTests after KT-18833 fix 2018-04-23 15:31:31 +02:00
Dimitrios (Dimi) Liapis 2960a558d7 Fix typo
See gh-1803
2018-04-21 18:21:19 +02:00
Brian Clozel d69a281e5c Upgrade to Netty 4.1.24.Final 2018-04-21 09:31:29 +02:00
Rossen Stoyanchev d3ed7b624d In 5.0.x we don't have Flux/Mono error with Supplier
Issue: SPR-16726
2018-04-19 13:41:01 -04:00
Rossen Stoyanchev 66bd277671 Use StringDecoder to split SSE stream
ServerSentEventHttpMessageReader had logic to split on new lines
and buffer until an empty new line (start of a new event). To account
for random data chunking, it later re-assembled the lines for each
event and split again on new lines. However bufferUntil was still
unreliable a chunk may contain nothing but a newline, which doesn't
necessarily mean an empty newline in the overall SSE stream.

This commit simplifies the above by delegating the splitting of the
stream along newlines to StringDecoder.

Issue: SPR-16744
2018-04-19 11:38:43 -04:00
Rossen Stoyanchev 881343e928 Polish tests to use WebClient retrieve() 2018-04-19 11:38:43 -04:00
Daniel Kift 922fd1e785 Polish WebFlux reference documentation 2018-04-18 11:58:37 +02:00
nkjackzhang ea8317a1f9 Fix a typo in @Nullable Javadoc 2018-04-18 11:55:13 +02:00
Rossen Stoyanchev 053ffe808f Polish (minor) in AbstractMessageReaderArgumentResolver 2018-04-17 17:58:56 -04:00
Rossen Stoyanchev daa2d37ad4 Avoid creating Exception instance if not needed
Issue: SPR-16726
2018-04-17 17:58:46 -04:00
Juergen Hoeller f800df12e3 Correctly delegate to OrderUtils.getPriority for DecoratingProxy
Issue: SPR-16739

(cherry picked from commit 2f4010e)
2018-04-17 23:38:30 +02:00
Juergen Hoeller 26652a6b83 Avoid repeated superclass introspection in findAnnotation(Method,...)
Issue: SPR-16730

(cherry picked from commit d78e27f)
2018-04-17 17:06:31 +02:00
Juergen Hoeller 4cd43dc793 Workaround for generic parameter types on inner class constructors
Issue: SPR-16734
2018-04-17 15:32:03 +02:00
sdeleuze 91c8b62817 Make ResponseSpec.expectBody Kotlin extension usable
Prior to this commit, due to KT-5464 type inference issue there was not
proper way to provide body expectations with WebTestClient. This commit
provides a workaround by updating the existing Kotlin extension to
return a Kotlin compatible API.

Issue: SPR-15692
2018-04-17 14:58:12 +02:00
Juergen Hoeller 9d37c099a8 OperatorMatches flags misguided evaluation attempts as FLAWED_PATTERN
Issue: SPR-16731

(cherry picked from commit d4a55a2)
2018-04-17 13:35:01 +02:00
Juergen Hoeller eb573d8b9e Restore original MethodMapTransactionAttributeSource matching rules
Issue: SPR-16733

(cherry picked from commit c5b524d)
2018-04-17 13:34:38 +02:00
Rossen Stoyanchev b312a62f64 Selector header name is exposed for configuration
Issue: SPR-16732
2018-04-16 23:58:47 -04:00
Rossen Stoyanchev 567733d2a1 Restore handling of 0 bytes read
Issue: SPR-16728
2018-04-16 10:01:51 -04:00
Juergen Hoeller 0f91f4b960 Local XMLUnit dependency declarations with consistent version 2.5.1
Includes upgrade to Undertow 1.4.24.

(cherry picked from commit 0754833)
2018-04-14 21:23:33 +02:00
Juergen Hoeller c1385f52c2 Polishing
(cherry picked from commit de4ff4b)
2018-04-14 21:03:59 +02:00
Sam Brannen c3bc125093 Suppress warning in SpringFailOnTimeoutTests 2018-04-14 16:44:47 +02:00
Juergen Hoeller b5922f75bb AspectJExpressionPointcut consistently resolves superinterface methods
Includes efficient check for same ClassLoader in ClassUtils.isVisible, efficient MethodMatchers check for IntroductionAwareMethodMatcher, and supertype method resolution in MethodMapTransactionAttributeSource.

Issue: SPR-16723

(cherry picked from commit b95e05d)
2018-04-14 15:49:55 +02:00
nkjackzhang bbe850d33a Fix typo in javadoc
Closes gh-1791
2018-04-13 13:16:40 +02:00
Juergen Hoeller 295929cc16 Cache-safety check for sibling loaders resolving the same classes
Issue: SPR-16714
2018-04-12 21:08:25 +02:00
Juergen Hoeller 4763154193 Consistent getTypeForFactoryMethod result for parameterized method
Issue: SPR-16720

(cherry picked from commit 6184c4e)
2018-04-12 21:08:14 +02:00
Juergen Hoeller 8f7e5e7c1a Fine-tuned JCA MessageEndpoint exception logging and propagation
Issue: SPR-16717

(cherry picked from commit 8e1ecec)
2018-04-12 21:07:44 +02:00
Juergen Hoeller cd79966c52 Revised reference example for linkable controller method signature
Issue: SPR-16710

(cherry picked from commit 7ee6130)
2018-04-12 21:07:39 +02:00
Brian Clozel 7631aa6062 Switch to Reactor Bismusth SNAPSHOTs 2018-04-12 17:01:24 +02:00
Sam Brannen 02e09098e4 Expand scope of SpringFailOnTimeoutTests
Issue: SPR-16716
2018-04-12 11:00:45 +02:00
Igor Suhorukov 230c8f93e8 Throw exception from user code in SpringFailOnTimeout even if a timeout occurs
Issue: SPR-16717
2018-04-12 11:00:35 +02:00
Rossen Stoyanchev c4296fa785 Remove write pausing in Undertow response
Using the simple example shown in the ticket but switching from
Mono<String> to Flux<String> (and 5,000,000 onNext calls) shows that
constant pausing causes significant overhead and is not worth the
trouble vs ignoring the onWritePossible in REQUESTED state.

Issue: SPR-16702
2018-04-11 14:37:35 -04:00
Rossen Stoyanchev ab78854f1b Avoid inifinite recursion in UndertowServerHttpResponse
Undertow does not provide a way to check if we can write so with the
current implementation of isWritePossible, deep recursion can occur
when writing slows down. We now use a flag to keep track of write
ChannelListener callbacks.

This commit also addresses a related issue in
AbstractListenerWriteProcessor that went undected since #3c2d186
where after a large (single) buffer that is not written fully, the
completion signal is processed before the all data is written.

Issue: SPR-16702
2018-04-11 14:37:19 -04:00
Juergen Hoeller 96a465a749 Upgrade to Tomcat 8.5.30 2018-04-11 16:27:34 +02:00
Juergen Hoeller 861b9dc938 Proper exception for controller method return types that do not work with MvcUriComponentsBuilder (e.g. final classes)
Includes direct use of ControllerMethodInvocationInterceptor for return type Object, avoiding the attempt to generate an Object subclass.

Issue: SPR-16710

(cherry picked from commit f28a5d0)
2018-04-11 16:27:14 +02:00
sdeleuze eda2720471 Add default ctor to Reactive UrlBasedCorsConfigurationSource
Issue: SPR-16712
2018-04-11 14:41:06 +02:00
Juergen Hoeller 7fe28ce8b7 Upgrade to Netty 4.1.23 and TestNG 6.14.3 2018-04-11 13:29:37 +02:00
Juergen Hoeller de8c4179fb Polishing 2018-04-11 13:29:15 +02:00
Juergen Hoeller 433877e5cb AnnotationUtils.getAnnotation non-null check for synthesizeAnnotation
Issue: SPR-16708

(cherry picked from commit da80502)
2018-04-11 13:28:53 +02:00
Juergen Hoeller ffa4f03fd4 Unwind _TestTypes to top-level public test classes in AOP test suite
(cherry picked from commit cdaa247)
2018-04-11 13:28:39 +02:00
Juergen Hoeller 7068282e1f Remove bogus DataSource test from JpaTransactionManagerTests
(cherry picked from commit ff53d78)
2018-04-11 13:28:33 +02:00
sdeleuze 3879179927 Document why "charset=UTF-8" is specified for JSON
Issue: SPR-14715
2018-04-09 12:01:21 +02:00
KwonJH 007da2a58d Fix Java 9 link in the reference documentation 2018-04-09 11:13:25 +02:00
sdeleuze 1be585562f Improve Kotlin + bean validation documentation
Issue: SPR-16701
2018-04-09 10:18:06 +02:00
Rossen Stoyanchev 7a896d7d80 TestDispatcherServlet unwraps to find mock request
Issue: SPR-16695
2018-04-06 11:04:29 -04:00
sdeleuze be1aaa06e7 Cleanup settings.gradle pluginManagement configuration 2018-04-04 11:11:38 +02:00
sdeleuze 2fa060f0e9 Fix Dokka reference to Spring Framework's Javadoc
This commit specifies a local packageListUrl and defines that dokka task
must be executed after the api task in order to be able to build KDoc
during the release process when the Spring Framework's Javadoc is not
published yet.

Issue: SPR-16687
2018-04-04 11:11:17 +02:00
Stephane Nicoll 4d2d889142 Initiate 5.0.x branch 2018-04-03 23:07:03 +02:00
Spring Buildmaster 4b9bc50fd0 Release version 5.0.5.RELEASE 2018-04-03 20:11:16 +00:00
693 changed files with 11181 additions and 8581 deletions
+2 -2
View File
@@ -38,7 +38,7 @@ it helps us to make a decision.
Reporting an issue or making a feature request is a great way to contribute. Your feedback
and the conversations that result from it provide a continuous flow of ideas.
Before you create a ticket, please take the time to [research first](#Discuss).
Before you create a ticket, please take the time to [research first](#discuss).
If creating a ticket after a discussion on StackOverflow, please provide a self-sufficient description in the ticket, independent of the details on StackOverview. We understand this is extra work but the issue tracker is an important place of record for design discussions and decisions that can often be referenced long after the fix version, for example to revisit decisions, to understand the origin of a feature, and so on.
@@ -64,7 +64,7 @@ You can contribute a source code change by submitting a pull request.
[Contributor License Agreement](https://cla.pivotal.io/sign/spring). You will also be reminded
automatically when you submit a pull request.
1. For all but the most trivial of contributions, please [create a ticket](#Create-a-Ticket).
1. For all but the most trivial of contributions, please [create a ticket](#create-a-ticket).
The purpose of the ticket is to understand and discuss the underlying issue or feature.
We use the JIRA issue tracker as the preferred place of record for conversations and
conclusions. In that sense discussions directly under a PR are more implementation detail
+43 -36
View File
@@ -14,8 +14,8 @@ buildscript {
plugins {
id "com.gradle.build-scan" version "1.8"
id "io.spring.dependency-management" version "1.0.3.RELEASE" apply false
id "org.jetbrains.kotlin.jvm" version "1.2.31" apply false
id "org.jetbrains.dokka" version "0.9.16"
id "org.jetbrains.kotlin.jvm" version "1.2.51" apply false
id "org.jetbrains.dokka" version "0.9.17"
id "org.asciidoctor.convert" version "1.5.6"
}
@@ -35,40 +35,54 @@ ext {
moduleProjects = subprojects.findAll {
!it.name.equals('spring-build-src') && !it.name.equals('spring-framework-bom')
}
aspectjVersion = "1.8.13"
freemarkerVersion = "2.3.27-incubating"
groovyVersion = "2.4.15"
hsqldbVersion = "2.4.1"
jackson2Version = "2.9.6"
jettyVersion = "9.4.11.v20180605"
junitJupiterVersion = "5.0.3"
junitPlatformVersion = "1.0.3"
junitVintageVersion = "4.12.3"
kotlinVersion = "1.2.51"
log4jVersion = "2.11.0"
nettyVersion = "4.1.25.Final"
reactorVersion = "Bismuth-SR10"
rxjavaVersion = "1.3.8"
rxjavaAdapterVersion = "1.2.1"
rxjava2Version = "2.1.16"
slf4jVersion = "1.7.25" // spring-jcl + consistent 3rd party deps
tiles3Version = "3.0.8"
tomcatVersion = "8.5.32"
undertowVersion = "1.4.25.Final"
gradleScriptDir = "${rootProject.projectDir}/gradle"
withoutJclOverSlf4J = {
exclude group: "org.slf4j", module: "jcl-over-slf4j"
}
}
configure(allprojects) { project ->
group = "org.springframework"
version = qualifyVersionIfNecessary(version)
ext.aspectjVersion = "1.8.13"
ext.freemarkerVersion = "2.3.27-incubating"
ext.groovyVersion = "2.4.15"
ext.hsqldbVersion = "2.4.0"
ext.jackson2Version = "2.9.5"
ext.jettyVersion = "9.4.9.v20180320"
ext.junitJupiterVersion = "5.0.3"
ext.junitPlatformVersion = "1.0.3"
ext.junitVintageVersion = "4.12.3"
ext.kotlinVersion = "1.2.31"
ext.log4jVersion = "2.11.0"
ext.nettyVersion = "4.1.22.Final"
ext.reactorVersion = "Bismuth-SR8"
ext.rxjavaVersion = "1.3.8"
ext.rxjavaAdapterVersion = "1.2.1"
ext.rxjava2Version = "2.1.12"
ext.slf4jVersion = "1.7.25" // spring-jcl + consistent 3rd party deps
ext.tiles3Version = "3.0.8"
ext.tomcatVersion = "8.5.29"
ext.undertowVersion = "1.4.23.Final"
ext.gradleScriptDir = "${rootProject.projectDir}/gradle"
apply plugin: "propdeps"
apply plugin: "java"
apply plugin: "test-source-set-dependencies"
apply plugin: "io.spring.dependency-management"
apply from: "${gradleScriptDir}/ide.gradle"
dependencyManagement {
resolutionStrategy {
cacheChangingModulesFor 0, 'seconds'
}
applyMavenExclusions = false
generatedPomCustomization {
enabled = false
}
}
apply plugin: "kotlin"
compileKotlin {
kotlinOptions {
@@ -96,7 +110,6 @@ configure(allprojects) { project ->
}
}
exclude group: "org.slf4j", module: "jcl-over-slf4j"
}
def commonCompilerArgs =
@@ -145,20 +158,19 @@ configure(allprojects) { project ->
testCompile("junit:junit:4.12") {
exclude group:'org.hamcrest', module:'hamcrest-core'
}
testCompile("org.mockito:mockito-core:2.12.0") {
testCompile("org.mockito:mockito-core:2.19.1") {
exclude group:'org.hamcrest', module:'hamcrest-core'
}
testCompile("com.nhaarman:mockito-kotlin:1.5.0") {
testCompile("com.nhaarman:mockito-kotlin:1.6.0") {
exclude module:'kotlin-stdlib'
exclude module:'kotlin-reflect'
exclude module:'mockito-core'
}
testCompile("org.hamcrest:hamcrest-all:1.3")
testCompile("org.xmlunit:xmlunit-matchers:2.3.0")
testRuntime("org.apache.logging.log4j:log4j-core:${log4jVersion}")
testRuntime("org.apache.logging.log4j:log4j-slf4j-impl:${log4jVersion}")
testRuntime("org.apache.logging.log4j:log4j-jul:${log4jVersion}")
// JSR-305 only used for non-required meta-annotations
// JSR-305 only used for non-required meta-annotations
compileOnly("com.google.code.findbugs:jsr305:3.0.2")
testCompileOnly("com.google.code.findbugs:jsr305:3.0.2")
}
@@ -239,7 +251,6 @@ configure(rootProject) {
description = "Spring Framework"
apply plugin: "groovy"
apply plugin: "io.spring.dependency-management"
apply from: "${gradleScriptDir}/jdiff.gradle"
apply from: "${gradleScriptDir}/docs.gradle"
@@ -247,10 +258,6 @@ configure(rootProject) {
imports {
mavenBom "io.projectreactor:reactor-bom:${reactorVersion}"
}
resolutionStrategy {
cacheChangingModulesFor 0, 'seconds'
}
applyMavenExclusions = false
}
// don't publish the default jar for the root project
@@ -272,7 +279,7 @@ configure(rootProject) {
testCompile("javax.servlet:javax.servlet-api:3.1.0")
testCompile("org.aspectj:aspectjweaver:${aspectjVersion}")
testCompile("org.hsqldb:hsqldb:${hsqldbVersion}")
testCompile("org.hibernate:hibernate-core:5.1.13.Final")
testCompile("org.hibernate:hibernate-core:5.1.14.Final")
}
artifacts {
+1 -1
View File
@@ -1 +1 @@
version=5.0.5.BUILD-SNAPSHOT
version=5.0.8.RELEASE
+10 -5
View File
@@ -49,12 +49,9 @@ task api(type: Javadoc) {
}
}
// Need https://github.com/Kotlin/dokka/issues/184 to be fixed to avoid "Can't find node by signature" log spam
dokka {
dependsOn {
subprojects.collect {
it.tasks.getByName("jar")
}
tasks.getByName("api")
}
doFirst {
classpath = subprojects.collect { project -> project.jar.outputs.files.getFiles() }.flatten()
@@ -69,6 +66,10 @@ dokka {
def kotlinDirs = project.sourceSets.main.kotlin.srcDirs.collect()
kotlinDirs -= project.sourceSets.main.java.srcDirs
})
externalDocumentationLink {
url = new URL("https://docs.spring.io/spring-framework/docs/$version/javadoc-api/")
packageListUrl = new File(buildDir, "api/package-list").toURI().toURL()
}
externalDocumentationLink {
url = new URL("http://projectreactor.io/docs/core/release/api/")
}
@@ -122,10 +123,14 @@ task docsZip(type: Zip, dependsOn: ['api', 'asciidoctor', 'dokka']) {
into "javadoc-api"
}
from (asciidoctor) {
from ("$asciidoctor.outputDir/html5") {
into "spring-framework-reference"
}
from ("$asciidoctor.outputDir/pdf") {
into "spring-framework-reference/pdf"
}
from (dokka) {
into "kdoc-api"
}
+5
View File
@@ -18,6 +18,11 @@ def customizePom(pom, gradleProject) {
"$dep.scope:$dep.groupId:$dep.artifactId"
}
def managedVersions = dependencyManagement.managedVersions
generatedPom.dependencies.findAll{dep -> !dep.version }.each { dep ->
dep.version = managedVersions["${dep.groupId}:${dep.artifactId}"]
}
// add all items necessary for maven central publication
generatedPom.project {
name = gradleProject.description
-19
View File
@@ -1,22 +1,3 @@
/*
pluginManagement {
repositories {
maven {
url "https://dl.bintray.com/kotlin/kotlin-eap-1.1"
}
gradlePluginPortal()
}
}
*/
// Workaround for https://github.com/Kotlin/dokka/issues/146
pluginManagement {
repositories {
jcenter()
gradlePluginPortal()
}
}
include "spring-aop"
include "spring-aspects"
include "spring-beans"
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,10 +50,11 @@ import org.springframework.lang.Nullable;
public interface MethodMatcher {
/**
* Perform static checking whether the given method matches. If this
* returns {@code false} or if the {@link #isRuntime()} method
* returns {@code false}, no runtime check (i.e. no.
* {@link #matches(java.lang.reflect.Method, Class, Object[])} call) will be made.
* Perform static checking whether the given method matches.
* <p>If this returns {@code false} or if the {@link #isRuntime()}
* method returns {@code false}, no runtime check (i.e. no
* {@link #matches(java.lang.reflect.Method, Class, Object[])} call)
* will be made.
* @param method the candidate method
* @param targetClass the target class (may be {@code null}, in which case
* the candidate class must be taken to be the method's declaring class)
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.aop.aspectj;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
@@ -289,10 +290,9 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
@Override
public boolean matches(Method method, @Nullable Class<?> targetClass, boolean beanHasIntroductions) {
public boolean matches(Method method, @Nullable Class<?> targetClass, boolean hasIntroductions) {
obtainPointcutExpression();
Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
ShadowMatch shadowMatch = getShadowMatch(targetMethod, method);
ShadowMatch shadowMatch = getTargetShadowMatch(method, targetClass);
// Special handling for this, target, @this, @target, @annotation
// in Spring - we can optimize since we know we have exactly this class,
@@ -305,7 +305,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
else {
// the maybe case
if (beanHasIntroductions) {
if (hasIntroductions) {
return true;
}
// A match test returned maybe - if there are any subtype sensitive variables
@@ -331,8 +331,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
@Override
public boolean matches(Method method, @Nullable Class<?> targetClass, Object... args) {
obtainPointcutExpression();
ShadowMatch shadowMatch = getShadowMatch(AopUtils.getMostSpecificMethod(method, targetClass), method);
ShadowMatch originalShadowMatch = getShadowMatch(method, method);
ShadowMatch shadowMatch = getTargetShadowMatch(method, targetClass);
// Bind Spring AOP proxy to AspectJ "this" and Spring AOP target to AspectJ target,
// consistent with return of MethodInvocationProceedingJoinPoint
@@ -367,7 +366,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
* <p>See SPR-2979 for the original bug.
*/
if (pmi != null && thisObject != null) { // there is a current invocation
RuntimeTestWalker originalMethodResidueTest = getRuntimeTestWalker(originalShadowMatch);
RuntimeTestWalker originalMethodResidueTest = getRuntimeTestWalker(getShadowMatch(method, method));
if (!originalMethodResidueTest.testThisInstanceOfResidue(thisObject.getClass())) {
return false;
}
@@ -427,6 +426,28 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
invocation.setUserAttribute(resolveExpression(), jpm);
}
private ShadowMatch getTargetShadowMatch(Method method, @Nullable Class<?> targetClass) {
Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
if (targetClass != null && targetMethod.getDeclaringClass().isInterface()) {
// Try to build the most specific interface possible for inherited methods to be
// considered for sub-interface matches as well, in particular for proxy classes.
// Note: AspectJ is only going to take Method.getDeclaringClass() into account.
Set<Class<?>> ifcs = ClassUtils.getAllInterfacesForClassAsSet(targetClass);
if (ifcs.size() > 1) {
try {
Class<?> compositeInterface = ClassUtils.createCompositeInterface(
ClassUtils.toClassArray(ifcs), targetClass.getClassLoader());
targetMethod = ClassUtils.getMostSpecificMethod(targetMethod, compositeInterface);
}
catch (IllegalArgumentException ex) {
// Implemented interfaces probably expose conflicting method signatures...
// Proceed with original target method.
}
}
}
return getShadowMatch(targetMethod, method);
}
private ShadowMatch getShadowMatch(Method targetMethod, Method originalMethod) {
// Avoid lock contention for known Methods through concurrent access...
ShadowMatch shadowMatch = this.shadowMatchCache.get(targetMethod);
@@ -434,9 +455,9 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
synchronized (this.shadowMatchCache) {
// Not found - now check again with full lock...
PointcutExpression fallbackExpression = null;
Method methodToMatch = targetMethod;
shadowMatch = this.shadowMatchCache.get(targetMethod);
if (shadowMatch == null) {
Method methodToMatch = targetMethod;
try {
try {
shadowMatch = obtainPointcutExpression().matchesMethodExecution(methodToMatch);
@@ -454,12 +475,16 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
fallbackExpression = null;
}
}
if (shadowMatch == null && targetMethod != originalMethod) {
if (targetMethod != originalMethod && (shadowMatch == null ||
(shadowMatch.neverMatches() && Proxy.isProxyClass(targetMethod.getDeclaringClass())))) {
// Fall back to the plain original method in case of no resolvable match or a
// negative match on a proxy class (which doesn't carry any annotations on its
// redeclared methods).
methodToMatch = originalMethod;
try {
shadowMatch = obtainPointcutExpression().matchesMethodExecution(methodToMatch);
}
catch (ReflectionWorldException ex3) {
catch (ReflectionWorldException ex) {
// Could neither introspect the target class nor the proxy class ->
// let's try the original method's declaring class before we give up...
try {
@@ -468,7 +493,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
shadowMatch = fallbackExpression.matchesMethodExecution(methodToMatch);
}
}
catch (ReflectionWorldException ex4) {
catch (ReflectionWorldException ex2) {
fallbackExpression = null;
}
}
@@ -542,6 +567,19 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
return sb.toString();
}
//---------------------------------------------------------------------
// Serialization support
//---------------------------------------------------------------------
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Rely on default serialization, just initialize state after deserialization.
ois.defaultReadObject();
// Initialize transient fields.
// pointcutExpression will be initialized lazily by checkReadyToMatch()
this.shadowMatchCache = new ConcurrentHashMap<>(32);
}
/**
* Handler for the Spring-specific {@code bean()} pointcut designator
@@ -638,20 +676,6 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
//---------------------------------------------------------------------
// Serialization support
//---------------------------------------------------------------------
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Rely on default serialization, just initialize state after deserialization.
ois.defaultReadObject();
// Initialize transient fields.
// pointcutExpression will be initialized lazily by checkReadyToMatch()
this.shadowMatchCache = new ConcurrentHashMap<>(32);
}
private static class DefensiveShadowMatch implements ShadowMatch {
private final ShadowMatch primary;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,17 +33,15 @@ import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Implementation of AspectJ ProceedingJoinPoint interface
* wrapping an AOP Alliance MethodInvocation.
* An implementation of the AspectJ {@link ProceedingJoinPoint} interface
* wrapping an AOP Alliance {@link org.aopalliance.intercept.MethodInvocation}.
*
* <p><b>Note</b>: the {@code getThis()} method returns the current Spring AOP proxy.
* <p><b>Note</b>: The {@code getThis()} method returns the current Spring AOP proxy.
* The {@code getTarget()} method returns the current Spring AOP target (which may be
* {@code null} if there is no target), and is a plain POJO without any advice.
* <b>If you want to call the object and have the advice take effect, use
* {@code getThis()}.</b> A common example is casting the object to an
* introduced interface in the implementation of an introduction.
*
* <p>Of course there is no such distinction between target and proxy in AspectJ.
* {@code null} if there is no target instance) as a plain POJO without any advice.
* <b>If you want to call the object and have the advice take effect, use {@code getThis()}.</b>
* A common example is casting the object to an introduced interface in the implementation of
* an introduction. There is no such distinction between target and proxy in AspectJ itself.
*
* @author Rod Johnson
* @author Juergen Hoeller
@@ -58,7 +56,7 @@ public class MethodInvocationProceedingJoinPoint implements ProceedingJoinPoint,
private final ProxyMethodInvocation methodInvocation;
@Nullable
private Object[] defensiveCopyOfArgs;
private Object[] args;
/** Lazily initialized signature object */
@Nullable
@@ -79,6 +77,7 @@ public class MethodInvocationProceedingJoinPoint implements ProceedingJoinPoint,
this.methodInvocation = methodInvocation;
}
@Override
public void set$AroundClosure(AroundClosure aroundClosure) {
throw new UnsupportedOperationException();
@@ -120,12 +119,10 @@ public class MethodInvocationProceedingJoinPoint implements ProceedingJoinPoint,
@Override
public Object[] getArgs() {
if (this.defensiveCopyOfArgs == null) {
Object[] argsSource = this.methodInvocation.getArguments();
this.defensiveCopyOfArgs = new Object[argsSource.length];
System.arraycopy(argsSource, 0, this.defensiveCopyOfArgs, 0, argsSource.length);
if (this.args == null) {
this.args = this.methodInvocation.getArguments().clone();
}
return this.defensiveCopyOfArgs;
return this.args;
}
@Override
@@ -133,7 +130,7 @@ public class MethodInvocationProceedingJoinPoint implements ProceedingJoinPoint,
if (this.signature == null) {
this.signature = new MethodSignatureImpl();
}
return signature;
return this.signature;
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,8 @@
package org.springframework.aop.aspectj.annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -87,8 +87,8 @@ public class BeanFactoryAspectJAdvisorsBuilder {
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new LinkedList<>();
aspectNames = new LinkedList<>();
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
for (String beanName : beanNames) {
@@ -138,7 +138,7 @@ public class BeanFactoryAspectJAdvisorsBuilder {
if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
List<Advisor> advisors = new LinkedList<>();
List<Advisor> advisors = new ArrayList<>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) {
@@ -20,8 +20,8 @@ import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import org.aopalliance.aop.Advice;
@@ -121,7 +121,7 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
List<Advisor> advisors = new LinkedList<>();
List<Advisor> advisors = new ArrayList<>();
for (Method method : getAdvisorMethods(aspectClass)) {
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
if (advisor != null) {
@@ -147,7 +147,7 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
}
private List<Method> getAdvisorMethods(Class<?> aspectClass) {
final List<Method> methods = new LinkedList<>();
final List<Method> methods = new ArrayList<>();
ReflectionUtils.doWithMethods(aspectClass, method -> {
// Exclude pointcuts
if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
@@ -22,7 +22,6 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -94,7 +93,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
* List of Advisors. If an Advice is added, it will be wrapped
* in an Advisor before being added to this List.
*/
private List<Advisor> advisors = new LinkedList<>();
private List<Advisor> advisors = new ArrayList<>();
/**
* Array updated on changes to the advisors list, which is easier
@@ -153,11 +152,12 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
* @see #setTargetSource
* @see #setTarget
*/
public void setTargetClass(Class<?> targetClass) {
public void setTargetClass(@Nullable Class<?> targetClass) {
this.targetSource = EmptyTargetSource.forClass(targetClass);
}
@Override
@Nullable
public Class<?> getTargetClass() {
return this.targetSource.getTargetClass();
}
@@ -474,7 +474,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
* for the given method, based on this configuration.
* @param method the proxied method
* @param targetClass the target class
* @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
* @return a List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
*/
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
MethodCacheKey cacheKey = new MethodCacheKey(method);
@@ -528,7 +528,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
/**
* Build a configuration-only copy of this AdvisedSupport,
* replacing the TargetSource
* replacing the TargetSource.
*/
AdvisedSupport getConfigurationOnlyCopy() {
AdvisedSupport copy = new AdvisedSupport();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -205,9 +205,8 @@ class CglibAopProxy implements AopProxy, Serializable {
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of class [" +
this.advised.getTargetClass() + "]: " +
"Common causes of this problem include using a final class or a non-visible class",
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
@@ -292,20 +291,20 @@ class CglibAopProxy implements AopProxy, Serializable {
// unadvised but can return this). May be required to expose the proxy.
Callback targetInterceptor;
if (exposeProxy) {
targetInterceptor = isStatic ?
targetInterceptor = (isStatic ?
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
}
else {
targetInterceptor = isStatic ?
targetInterceptor = (isStatic ?
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
}
// Choose a "direct to target" dispatcher (used for
// unadvised calls to static targets that cannot return this).
Callback targetDispatcher = isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();
Callback targetDispatcher = (isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());
Callback[] mainCallbacks = new Callback[] {
aopInterceptor, // for normal advice
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -53,7 +53,7 @@ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializ
// This is somewhat tricky... We have to process introductions first,
// but we need to preserve order in the ultimate list.
List<Object> interceptorList = new ArrayList<>(config.getAdvisors().length);
List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
@@ -63,9 +63,9 @@ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializ
// Add it conditionally.
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
if (mm.isRuntime()) {
// Creating a new object instance in the getInterceptors() method
// isn't a problem as we normally cache created chains.
@@ -99,8 +99,7 @@ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializ
* Determine whether the Advisors contain matching introductions.
*/
private static boolean hasMatchingIntroductions(Advised config, Class<?> actualClass) {
for (int i = 0; i < config.getAdvisors().length; i++) {
Advisor advisor = config.getAdvisors()[i];
for (Advisor advisor : config.getAdvisors()) {
if (advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (ia.getClassFilter().matches(actualClass)) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ public class ProxyCreatorSupport extends AdvisedSupport {
private AopProxyFactory aopProxyFactory;
private List<AdvisedSupportListener> listeners = new LinkedList<>();
private final List<AdvisedSupportListener> listeners = new LinkedList<>();
/** Set to true when the first AOP proxy has been created */
private boolean active = false;
@@ -651,7 +651,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
}
public String getBeanName() {
return beanName;
return this.beanName;
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,15 +31,15 @@ import org.springframework.aop.Advisor;
public interface AdvisorAdapterRegistry {
/**
* Return an Advisor wrapping the given advice.
* Return an {@link Advisor} wrapping the given advice.
* <p>Should by default at least support
* {@link org.aopalliance.intercept.MethodInterceptor},
* {@link org.springframework.aop.MethodBeforeAdvice},
* {@link org.springframework.aop.AfterReturningAdvice},
* {@link org.springframework.aop.ThrowsAdvice}.
* @param advice object that should be an advice
* @return an Advisor wrapping the given advice. Never returns {@code null}.
* If the advice parameter is an Advisor, return it.
* @return an Advisor wrapping the given advice (never {@code null};
* if the advice parameter is an Advisor, it is to be returned as-is)
* @throws UnknownAdviceTypeException if no registered advisor adapter
* can wrap the supposed advice
*/
@@ -48,21 +48,20 @@ public interface AdvisorAdapterRegistry {
/**
* Return an array of AOP Alliance MethodInterceptors to allow use of the
* given Advisor in an interception-based framework.
* <p>Don't worry about the pointcut associated with the Advisor,
* if it's a PointcutAdvisor: just return an interceptor.
* <p>Don't worry about the pointcut associated with the {@link Advisor}, if it is
* a {@link org.springframework.aop.PointcutAdvisor}: just return an interceptor.
* @param advisor Advisor to find an interceptor for
* @return an array of MethodInterceptors to expose this Advisor's behavior
* @throws UnknownAdviceTypeException if the Advisor type is
* not understood by any registered AdvisorAdapter.
* not understood by any registered AdvisorAdapter
*/
MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException;
/**
* Register the given AdvisorAdapter. Note that it is not necessary to register
* Register the given {@link AdvisorAdapter}. Note that it is not necessary to register
* adapters for an AOP Alliance Interceptors or Spring Advices: these must be
* automatically recognized by an AdvisorAdapterRegistry implementation.
* @param adapter AdvisorAdapter that understands a particular Advisor
* or Advice types
* automatically recognized by an {@code AdvisorAdapterRegistry} implementation.
* @param adapter AdvisorAdapter that understands particular Advisor or Advice types
*/
void registerAdvisorAdapter(AdvisorAdapter adapter);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,8 @@ import org.springframework.util.Assert;
* to use this class directly.
*
* @author Rod Johnson
* @see MethodBeforeAdviceInterceptor
* @see ThrowsAdviceInterceptor
*/
@SuppressWarnings("serial")
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
@@ -47,6 +49,7 @@ public class AfterReturningAdviceInterceptor implements MethodInterceptor, After
this.advice = advice;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
Object retVal = mi.proceed();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import java.io.Serializable;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.BeforeAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.util.Assert;
@@ -30,11 +31,13 @@ import org.springframework.util.Assert;
* to use this class directly.
*
* @author Rod Johnson
* @see AfterReturningAdviceInterceptor
* @see ThrowsAdviceInterceptor
*/
@SuppressWarnings("serial")
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {
private MethodBeforeAdvice advice;
private final MethodBeforeAdvice advice;
/**
@@ -46,9 +49,10 @@ public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Seriali
this.advice = advice;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,6 +51,8 @@ import org.springframework.util.Assert;
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see MethodBeforeAdviceInterceptor
* @see AfterReturningAdviceInterceptor
*/
public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
@@ -67,9 +69,8 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
/**
* Create a new ThrowsAdviceInterceptor for the given ThrowsAdvice.
* @param throwsAdvice the advice object that defines the exception
* handler methods (usually a {@link org.springframework.aop.ThrowsAdvice}
* implementation)
* @param throwsAdvice the advice object that defines the exception handler methods
* (usually a {@link org.springframework.aop.ThrowsAdvice} implementation)
*/
public ThrowsAdviceInterceptor(Object throwsAdvice) {
Assert.notNull(throwsAdvice, "Advice must not be null");
@@ -78,13 +79,14 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
Method[] methods = throwsAdvice.getClass().getMethods();
for (Method method : methods) {
if (method.getName().equals(AFTER_THROWING) &&
(method.getParameterCount() == 1 || method.getParameterCount() == 4) &&
Throwable.class.isAssignableFrom(method.getParameterTypes()[method.getParameterCount() - 1])
) {
// Have an exception handler
this.exceptionHandlerMap.put(method.getParameterTypes()[method.getParameterCount() - 1], method);
if (logger.isDebugEnabled()) {
logger.debug("Found exception handler method: " + method);
(method.getParameterCount() == 1 || method.getParameterCount() == 4)) {
Class<?> throwableParam = method.getParameterTypes()[method.getParameterCount() - 1];
if (Throwable.class.isAssignableFrom(throwableParam)) {
// An exception handler to register...
this.exceptionHandlerMap.put(throwableParam, method);
if (logger.isDebugEnabled()) {
logger.debug("Found exception handler method on throws advice: " + method);
}
}
}
}
@@ -95,14 +97,33 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
}
}
/**
* Return the number of handler methods in this advice.
*/
public int getHandlerMethodCount() {
return this.exceptionHandlerMap.size();
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
catch (Throwable ex) {
Method handlerMethod = getExceptionHandler(ex);
if (handlerMethod != null) {
invokeHandlerMethod(mi, ex, handlerMethod);
}
throw ex;
}
}
/**
* Determine the exception handle method. Can return null if not found.
* Determine the exception handle method for the given exception.
* @param exception the exception thrown
* @return a handler for the given exception type
* @return a handler for the given exception type, or {@code null} if none found
*/
@Nullable
private Method getExceptionHandler(Throwable exception) {
@@ -121,24 +142,10 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
return handler;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
catch (Throwable ex) {
Method handlerMethod = getExceptionHandler(ex);
if (handlerMethod != null) {
invokeHandlerMethod(mi, ex, handlerMethod);
}
throw ex;
}
}
private void invokeHandlerMethod(MethodInvocation mi, Throwable ex, Method method) throws Throwable {
Object[] handlerArgs;
if (method.getParameterCount() == 1) {
handlerArgs = new Object[] { ex };
handlerArgs = new Object[] {ex};
}
else {
handlerArgs = new Object[] {mi.getMethod(), mi.getArguments(), mi.getThis(), ex};
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,7 @@
package org.springframework.aop.framework.autoproxy;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -45,7 +45,7 @@ public class BeanFactoryAdvisorRetrievalHelper {
private final ConfigurableListableBeanFactory beanFactory;
@Nullable
private String[] cachedAdvisorBeanNames;
private volatile String[] cachedAdvisorBeanNames;
/**
@@ -66,22 +66,19 @@ public class BeanFactoryAdvisorRetrievalHelper {
*/
public List<Advisor> findAdvisorBeans() {
// Determine list of advisor bean names, if not cached already.
String[] advisorNames = null;
synchronized (this) {
advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the auto-proxy creator apply to them!
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
this.cachedAdvisorBeanNames = advisorNames;
}
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the auto-proxy creator apply to them!
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
this.cachedAdvisorBeanNames = advisorNames;
}
if (advisorNames.length == 0) {
return new LinkedList<>();
return new ArrayList<>();
}
List<Advisor> advisors = new LinkedList<>();
List<Advisor> advisors = new ArrayList<>();
for (String name : advisorNames) {
if (isEligibleBean(name)) {
if (this.beanFactory.isCurrentlyInCreation(name)) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,13 +29,13 @@ import org.apache.commons.logging.LogFactory;
*/
public class SimpleAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
private final Log logger = LogFactory.getLog(SimpleAsyncUncaughtExceptionHandler.class);
private static final Log logger = LogFactory.getLog(SimpleAsyncUncaughtExceptionHandler.class);
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
if (logger.isErrorEnabled()) {
logger.error(String.format("Unexpected error occurred invoking async " +
"method '%s'.", method), ex);
logger.error("Unexpected error occurred invoking async method: " + method, ex);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -131,8 +131,9 @@ public abstract class AbstractRegexpMethodPointcut extends StaticMethodMatcherPo
*/
@Override
public boolean matches(Method method, @Nullable Class<?> targetClass) {
return ((targetClass != null && matchesPattern(ClassUtils.getQualifiedMethodName(method, targetClass))) ||
matchesPattern(ClassUtils.getQualifiedMethodName(method)));
return ((targetClass != null && targetClass != method.getDeclaringClass() &&
matchesPattern(ClassUtils.getQualifiedMethodName(method, targetClass))) ||
matchesPattern(ClassUtils.getQualifiedMethodName(method, method.getDeclaringClass())));
}
/**
@@ -20,8 +20,8 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@@ -192,8 +192,7 @@ public abstract class AopUtils {
* @see org.springframework.util.ClassUtils#getMostSpecificMethod
*/
public static Method getMostSpecificMethod(Method method, @Nullable Class<?> targetClass) {
Class<?> specificTargetClass = (targetClass != null && !Proxy.isProxyClass(targetClass) ?
ClassUtils.getUserClass(targetClass) : null);
Class<?> specificTargetClass = (targetClass != null ? ClassUtils.getUserClass(targetClass) : null);
Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, specificTargetClass);
// If we are dealing with method with generic parameters, find the original method.
return BridgeMethodResolver.findBridgedMethod(resolvedMethod);
@@ -247,8 +246,8 @@ public abstract class AopUtils {
for (Class<?> clazz : classes) {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
for (Method method : methods) {
if ((introductionAwareMethodMatcher != null &&
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
if (introductionAwareMethodMatcher != null ?
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) :
methodMatcher.matches(method, targetClass)) {
return true;
}
@@ -306,7 +305,7 @@ public abstract class AopUtils {
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
List<Advisor> eligibleAdvisors = new LinkedList<>();
List<Advisor> eligibleAdvisors = new ArrayList<>();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -131,7 +131,7 @@ public class ControlFlowPointcut implements Pointcut, ClassFilter, MethodMatcher
return false;
}
ControlFlowPointcut that = (ControlFlowPointcut) other;
return (this.clazz.equals(that.clazz)) && ObjectUtils.nullSafeEquals(that.methodName, this.methodName);
return (this.clazz.equals(that.clazz)) && ObjectUtils.nullSafeEquals(this.methodName, that.methodName);
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,8 @@ import org.springframework.lang.Nullable;
/**
* Convenient abstract superclass for dynamic method matchers,
* which do care about arguments at runtime.
*
* @author Rod Johnson
*/
public abstract class DynamicMethodMatcher implements MethodMatcher {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -90,8 +90,8 @@ public abstract class MethodMatchers {
*/
public static boolean matches(MethodMatcher mm, Method method, @Nullable Class<?> targetClass, boolean hasIntroductions) {
Assert.notNull(mm, "MethodMatcher must not be null");
return ((mm instanceof IntroductionAwareMethodMatcher &&
((IntroductionAwareMethodMatcher) mm).matches(method, targetClass, hasIntroductions)) ||
return (mm instanceof IntroductionAwareMethodMatcher ?
((IntroductionAwareMethodMatcher) mm).matches(method, targetClass, hasIntroductions) :
mm.matches(method, targetClass));
}
@@ -144,23 +144,20 @@ public abstract class MethodMatchers {
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(obj instanceof UnionMethodMatcher)) {
if (!(other instanceof UnionMethodMatcher)) {
return false;
}
UnionMethodMatcher that = (UnionMethodMatcher) obj;
UnionMethodMatcher that = (UnionMethodMatcher) other;
return (this.mm1.equals(that.mm1) && this.mm2.equals(that.mm2));
}
@Override
public int hashCode() {
int hashCode = 17;
hashCode = 37 * hashCode + this.mm1.hashCode();
hashCode = 37 * hashCode + this.mm2.hashCode();
return hashCode;
return 37 * this.mm1.hashCode() + this.mm2.hashCode();
}
}
@@ -209,6 +206,12 @@ public abstract class MethodMatchers {
}
return (this.cf1.equals(otherCf1) && this.cf2.equals(otherCf2));
}
@Override
public int hashCode() {
// Allow for matching with regular UnionMethodMatcher by providing same hash...
return super.hashCode();
}
}
@@ -231,18 +234,18 @@ public abstract class MethodMatchers {
@Override
public boolean matches(Method method, @Nullable Class<?> targetClass, boolean hasIntroductions) {
return MethodMatchers.matches(this.mm1, method, targetClass, hasIntroductions) &&
MethodMatchers.matches(this.mm2, method, targetClass, hasIntroductions);
return (MethodMatchers.matches(this.mm1, method, targetClass, hasIntroductions) &&
MethodMatchers.matches(this.mm2, method, targetClass, hasIntroductions));
}
@Override
public boolean matches(Method method, @Nullable Class<?> targetClass) {
return this.mm1.matches(method, targetClass) && this.mm2.matches(method, targetClass);
return (this.mm1.matches(method, targetClass) && this.mm2.matches(method, targetClass));
}
@Override
public boolean isRuntime() {
return this.mm1.isRuntime() || this.mm2.isRuntime();
return (this.mm1.isRuntime() || this.mm2.isRuntime());
}
@Override
@@ -250,10 +253,10 @@ public abstract class MethodMatchers {
// Because a dynamic intersection may be composed of a static and dynamic part,
// we must avoid calling the 3-arg matches method on a dynamic matcher, as
// it will probably be an unsupported operation.
boolean aMatches = this.mm1.isRuntime() ?
this.mm1.matches(method, targetClass, args) : this.mm1.matches(method, targetClass);
boolean bMatches = this.mm2.isRuntime() ?
this.mm2.matches(method, targetClass, args) : this.mm2.matches(method, targetClass);
boolean aMatches = (this.mm1.isRuntime() ?
this.mm1.matches(method, targetClass, args) : this.mm1.matches(method, targetClass));
boolean bMatches = (this.mm2.isRuntime() ?
this.mm2.matches(method, targetClass, args) : this.mm2.matches(method, targetClass));
return aMatches && bMatches;
}
@@ -271,10 +274,7 @@ public abstract class MethodMatchers {
@Override
public int hashCode() {
int hashCode = 17;
hashCode = 37 * hashCode + this.mm1.hashCode();
hashCode = 37 * hashCode + this.mm2.hashCode();
return hashCode;
return 37 * this.mm1.hashCode() + this.mm2.hashCode();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,8 @@ package org.springframework.aop.support;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.springframework.lang.Nullable;
@@ -38,7 +38,7 @@ import org.springframework.util.PatternMatchUtils;
@SuppressWarnings("serial")
public class NameMatchMethodPointcut extends StaticMethodMatcherPointcut implements Serializable {
private List<String> mappedNames = new LinkedList<>();
private List<String> mappedNames = new ArrayList<>();
/**
@@ -55,11 +55,8 @@ public class NameMatchMethodPointcut extends StaticMethodMatcherPointcut impleme
* Matching will be the union of all these; if any match,
* the pointcut matches.
*/
public void setMappedNames(@Nullable String... mappedNames) {
this.mappedNames = new LinkedList<>();
if (mappedNames != null) {
this.mappedNames.addAll(Arrays.asList(mappedNames));
}
public void setMappedNames(String... mappedNames) {
this.mappedNames = new ArrayList<>(Arrays.asList(mappedNames));
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,8 @@ import java.io.Serializable;
import org.springframework.aop.ClassFilter;
/**
* Simple ClassFilter implementation that passes classes (and optionally subclasses)
* Simple ClassFilter implementation that passes classes (and optionally subclasses).
*
* @author Rod Johnson
*/
@SuppressWarnings("serial")
@@ -37,7 +38,7 @@ public class RootClassFilter implements ClassFilter, Serializable {
@Override
public boolean matches(Class<?> candidate) {
return clazz.isAssignableFrom(candidate);
return this.clazz.isAssignableFrom(candidate);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,8 @@ import org.springframework.lang.Nullable;
/**
* Convenient abstract superclass for static method matchers, which don't care
* about arguments at runtime.
*
* @author Rod Johnson
*/
public abstract class StaticMethodMatcher implements MethodMatcher {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.aop.support.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.support.StaticMethodMatcher;
@@ -71,6 +72,10 @@ public class AnnotationMethodMatcher extends StaticMethodMatcher {
if (matchesMethod(method)) {
return true;
}
// Proxy classes never have annotations on their redeclared methods.
if (targetClass != null && Proxy.isProxyClass(targetClass)) {
return false;
}
// The method may be on an interface, so let's check on the target class as well.
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
return (specificMethod != method && matchesMethod(specificMethod));
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,8 +74,8 @@ public abstract class AbstractPrototypeBasedTargetSource extends AbstractBeanFac
* @param target the bean instance to destroy
*/
protected void destroyPrototypeInstance(Object target) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'");
if (logger.isDebugEnabled()) {
logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'");
}
if (getBeanFactory() instanceof ConfigurableBeanFactory) {
((ConfigurableBeanFactory) getBeanFactory()).destroyBean(getTargetBeanName(), target);
@@ -85,7 +85,7 @@ public abstract class AbstractPrototypeBasedTargetSource extends AbstractBeanFac
((DisposableBean) target).destroy();
}
catch (Throwable ex) {
logger.error("Couldn't invoke destroy method of bean with name '" + getTargetBeanName() + "'", ex);
logger.error("Destroy method on bean with name '" + getTargetBeanName() + "' threw an exception", ex);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,6 @@
package org.springframework.aop.aspectj;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.junit.Test;
@@ -30,13 +27,7 @@ import org.junit.Test;
* @author Adrian Colyer
* @author Chris Beams
*/
public class AspectJAdviceParameterNameDiscoverAnnotationTests
extends AspectJAdviceParameterNameDiscovererTests {
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {}
public void pjpAndAnAnnotation(ProceedingJoinPoint pjp, MyAnnotation ann) {}
public class AspectJAdviceParameterNameDiscoverAnnotationTests extends AspectJAdviceParameterNameDiscovererTests {
@Test
public void testAnnotationBinding() {
@@ -45,4 +36,9 @@ public class AspectJAdviceParameterNameDiscoverAnnotationTests
new String[] {"thisJoinPoint","ann"});
}
public void pjpAndAnAnnotation(ProceedingJoinPoint pjp, MyAnnotation ann) {}
@interface MyAnnotation {}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import java.lang.reflect.Method;
@@ -34,47 +35,6 @@ import static org.junit.Assert.*;
*/
public class AspectJAdviceParameterNameDiscovererTests {
// methods to discover parameter names for
public void noArgs() {
}
public void tjp(JoinPoint jp) {
}
public void tjpsp(JoinPoint.StaticPart tjpsp) {
}
public void twoJoinPoints(JoinPoint jp1, JoinPoint jp2) {
}
public void oneThrowable(Exception ex) {
}
public void jpAndOneThrowable(JoinPoint jp, Exception ex) {
}
public void jpAndTwoThrowables(JoinPoint jp, Exception ex, Error err) {
}
public void oneObject(Object x) {
}
public void twoObjects(Object x, Object y) {
}
public void onePrimitive(int x) {
}
public void oneObjectOnePrimitive(Object x, int y) {
}
public void oneThrowableOnePrimitive(Throwable x, int y) {
}
public void theBigOne(JoinPoint jp, Throwable x, int y, Object foo) {
}
@Test
public void testNoArgs() {
assertParameterNames(getMethod("noArgs"), "execution(* *(..))", new String[0]);
@@ -221,22 +181,26 @@ public class AspectJAdviceParameterNameDiscovererTests {
@Test
public void testThisAndPrimitive() {
assertParameterNames(getMethod("oneObjectOnePrimitive"), "args(count) && this(obj)", new String[] {"obj", "count"});
assertParameterNames(getMethod("oneObjectOnePrimitive"), "args(count) && this(obj)",
new String[] {"obj", "count"});
}
@Test
public void testTargetAndPrimitive() {
assertParameterNames(getMethod("oneObjectOnePrimitive"), "args(count) && target(obj)", new String[] {"obj", "count"});
assertParameterNames(getMethod("oneObjectOnePrimitive"), "args(count) && target(obj)",
new String[] {"obj", "count"});
}
@Test
public void testThrowingAndPrimitive() {
assertParameterNames(getMethod("oneThrowableOnePrimitive"), "args(count)", null, "ex", new String[] {"ex", "count"});
assertParameterNames(getMethod("oneThrowableOnePrimitive"), "args(count)", null, "ex",
new String[] {"ex", "count"});
}
@Test
public void testAllTogetherNow() {
assertParameterNames(getMethod("theBigOne"), "this(foo) && args(x)", null, "ex", new String[] {"thisJoinPoint", "ex", "x", "foo"});
assertParameterNames(getMethod("theBigOne"), "this(foo) && args(x)", null, "ex",
new String[] {"thisJoinPoint", "ex", "x", "foo"});
}
@Test
@@ -253,8 +217,8 @@ public class AspectJAdviceParameterNameDiscovererTests {
protected Method getMethod(String name) {
// assumes no overloading of test methods...
Method[] candidates = this.getClass().getMethods();
// Assumes no overloading of test methods...
Method[] candidates = getClass().getMethods();
for (Method candidate : candidates) {
if (candidate.getName().equals(name)) {
return candidate;
@@ -268,8 +232,8 @@ public class AspectJAdviceParameterNameDiscovererTests {
assertParameterNames(method, pointcut, null, null, parameterNames);
}
protected void assertParameterNames(Method method, String pointcut, String returning, String throwing,
String[] parameterNames) {
protected void assertParameterNames(
Method method, String pointcut, String returning, String throwing, String[] parameterNames) {
assertEquals("bad test specification, must have same number of parameter names as method arguments",
method.getParameterCount(), parameterNames.length);
@@ -300,8 +264,8 @@ public class AspectJAdviceParameterNameDiscovererTests {
assertException(method, pointcut, null, null, exceptionType, message);
}
protected void assertException(Method method, String pointcut, String returning, String throwing,
Class<?> exceptionType, String message) {
protected void assertException(
Method method, String pointcut, String returning, String throwing, Class<?> exceptionType, String message) {
AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut);
discoverer.setRaiseExceptions(true);
@@ -333,4 +297,46 @@ public class AspectJAdviceParameterNameDiscovererTests {
return sb.toString();
}
// Methods to discover parameter names for
public void noArgs() {
}
public void tjp(JoinPoint jp) {
}
public void tjpsp(JoinPoint.StaticPart tjpsp) {
}
public void twoJoinPoints(JoinPoint jp1, JoinPoint jp2) {
}
public void oneThrowable(Exception ex) {
}
public void jpAndOneThrowable(JoinPoint jp, Exception ex) {
}
public void jpAndTwoThrowables(JoinPoint jp, Exception ex, Error err) {
}
public void oneObject(Object x) {
}
public void twoObjects(Object x, Object y) {
}
public void onePrimitive(int x) {
}
public void oneObjectOnePrimitive(Object x, int y) {
}
public void oneThrowableOnePrimitive(Throwable x, int y) {
}
public void theBigOne(JoinPoint jp, Throwable x, int y, Object foo) {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -218,38 +218,27 @@ public class AspectJExpressionPointcutTests {
@Test
public void testSimpleAdvice() {
String expression = "execution(int org.springframework.tests.sample.beans.TestBean.getAge())";
CallCountingInterceptor interceptor = new CallCountingInterceptor();
TestBean testBean = getAdvisedProxy(expression, interceptor);
assertEquals("Calls should be 0", 0, interceptor.getCount());
testBean.getAge();
assertEquals("Calls should be 1", 1, interceptor.getCount());
testBean.setAge(90);
assertEquals("Calls should still be 1", 1, interceptor.getCount());
}
@Test
public void testDynamicMatchingProxy() {
String expression = "execution(void org.springframework.tests.sample.beans.TestBean.setSomeNumber(Number)) && args(Double)";
CallCountingInterceptor interceptor = new CallCountingInterceptor();
TestBean testBean = getAdvisedProxy(expression, interceptor);
assertEquals("Calls should be 0", 0, interceptor.getCount());
testBean.setSomeNumber(new Double(30));
assertEquals("Calls should be 1", 1, interceptor.getCount());
testBean.setSomeNumber(new Integer(90));
assertEquals("Calls should be 1", 1, interceptor.getCount());
}
@@ -291,7 +280,7 @@ public class AspectJExpressionPointcutTests {
}
@Test
public void testWithUnsupportedPointcutPrimitive() throws Exception {
public void testWithUnsupportedPointcutPrimitive() {
String expression = "call(int org.springframework.tests.sample.beans.TestBean.getAge())";
try {
@@ -301,7 +290,6 @@ public class AspectJExpressionPointcutTests {
catch (UnsupportedPointcutPrimitiveException ex) {
assertEquals("Should not support call pointcut", PointcutPrimitive.CALL, ex.getUnsupportedPrimitive());
}
}
@Test
@@ -332,6 +320,7 @@ public class AspectJExpressionPointcutTests {
// Empty
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -77,6 +77,7 @@ public class BeanNamePointcutMatchingTests {
assertMisMatch("someName", "!bean(someName) || bean(someOtherName)");
}
private void assertMatch(String beanName, String pcExpression) {
assertTrue("Unexpected mismatch for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"",
matches(beanName, pcExpression));
@@ -98,4 +99,5 @@ public class BeanNamePointcutMatchingTests {
pointcut.setExpression(pcExpression);
return pointcut.matches(TestBean.class);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,30 +26,30 @@ import org.junit.Test;
import test.annotation.EmptySpringAnnotation;
import test.annotation.transaction.Tx;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.*;
/**
* Java5-specific {@link AspectJExpressionPointcutTests}.
* Java 5 specific {@link AspectJExpressionPointcutTests}.
*
* @author Rod Johnson
* @author Chris Beams
*/
public class TigerAspectJExpressionPointcutTests {
// TODO factor into static in AspectJExpressionPointcut
private Method getAge;
private Map<String,Method> methodsOnHasGeneric = new HashMap<>();
private final Map<String, Method> methodsOnHasGeneric = new HashMap<>();
@Before
public void setUp() throws NoSuchMethodException {
public void setup() throws NoSuchMethodException {
getAge = TestBean.class.getMethod("getAge");
// Assumes no overloading
for (Method m : HasGeneric.class.getMethods()) {
methodsOnHasGeneric.put(m.getName(), m);
for (Method method : HasGeneric.class.getMethods()) {
methodsOnHasGeneric.put(method.getName(), method);
}
}
@@ -74,7 +74,7 @@ public class TigerAspectJExpressionPointcutTests {
}
@Test
public void testMatchVarargs() throws SecurityException, NoSuchMethodException {
public void testMatchVarargs() throws Exception {
@SuppressWarnings("unused")
class MyTemplate {
@@ -87,11 +87,6 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut jdbcVarArgs = new AspectJExpressionPointcut();
jdbcVarArgs.setExpression(expression);
// TODO: the expression above no longer matches Object[]
// assertFalse(jdbcVarArgs.matches(
// JdbcTemplate.class.getMethod("queryForInt", String.class, Object[].class),
// JdbcTemplate.class));
assertTrue(jdbcVarArgs.matches(
MyTemplate.class.getMethod("queryForInt", String.class, Object[].class),
MyTemplate.class));
@@ -105,19 +100,19 @@ public class TigerAspectJExpressionPointcutTests {
}
@Test
public void testMatchAnnotationOnClassWithAtWithin() throws SecurityException, NoSuchMethodException {
public void testMatchAnnotationOnClassWithAtWithin() throws Exception {
String expression = "@within(test.annotation.transaction.Tx)";
testMatchAnnotationOnClass(expression);
}
@Test
public void testMatchAnnotationOnClassWithoutBinding() throws SecurityException, NoSuchMethodException {
public void testMatchAnnotationOnClassWithoutBinding() throws Exception {
String expression = "within(@test.annotation.transaction.Tx *)";
testMatchAnnotationOnClass(expression);
}
@Test
public void testMatchAnnotationOnClassWithSubpackageWildcard() throws SecurityException, NoSuchMethodException {
public void testMatchAnnotationOnClassWithSubpackageWildcard() throws Exception {
String expression = "within(@(test.annotation..*) *)";
AspectJExpressionPointcut springAnnotatedPc = testMatchAnnotationOnClass(expression);
assertFalse(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class), TestBean.class));
@@ -129,12 +124,12 @@ public class TigerAspectJExpressionPointcutTests {
}
@Test
public void testMatchAnnotationOnClassWithExactPackageWildcard() throws SecurityException, NoSuchMethodException {
public void testMatchAnnotationOnClassWithExactPackageWildcard() throws Exception {
String expression = "within(@(test.annotation.transaction.*) *)";
testMatchAnnotationOnClass(expression);
}
private AspectJExpressionPointcut testMatchAnnotationOnClass(String expression) throws SecurityException, NoSuchMethodException {
private AspectJExpressionPointcut testMatchAnnotationOnClass(String expression) throws Exception {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
@@ -147,7 +142,7 @@ public class TigerAspectJExpressionPointcutTests {
}
@Test
public void testAnnotationOnMethodWithFQN() throws SecurityException, NoSuchMethodException {
public void testAnnotationOnMethodWithFQN() throws Exception {
String expression = "@annotation(test.annotation.transaction.Tx)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
@@ -161,28 +156,56 @@ public class TigerAspectJExpressionPointcutTests {
}
@Test
public void testAnnotationOnMethodWithWildcard() throws SecurityException, NoSuchMethodException {
public void testAnnotationOnCglibProxyMethod() throws Exception {
String expression = "@annotation(test.annotation.transaction.Tx)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
ProxyFactory factory = new ProxyFactory(new BeanA());
factory.setProxyTargetClass(true);
BeanA proxy = (BeanA) factory.getProxy();
assertTrue(ajexp.matches(BeanA.class.getMethod("getAge"), proxy.getClass()));
}
@Test
public void testAnnotationOnDynamicProxyMethod() throws Exception {
String expression = "@annotation(test.annotation.transaction.Tx)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
ProxyFactory factory = new ProxyFactory(new BeanA());
factory.setProxyTargetClass(false);
IBeanA proxy = (IBeanA) factory.getProxy();
assertTrue(ajexp.matches(IBeanA.class.getMethod("getAge"), proxy.getClass()));
}
@Test
public void testAnnotationOnMethodWithWildcard() throws Exception {
String expression = "execution(@(test.annotation..*) * *(..))";
AspectJExpressionPointcut anySpringMethodAnnotation = new AspectJExpressionPointcut();
anySpringMethodAnnotation.setExpression(expression);
assertFalse(anySpringMethodAnnotation.matches(getAge, TestBean.class));
assertFalse(anySpringMethodAnnotation.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class));
assertFalse(anySpringMethodAnnotation.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(anySpringMethodAnnotation.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class));
assertFalse(anySpringMethodAnnotation.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class));
assertTrue(anySpringMethodAnnotation.matches(BeanA.class.getMethod("getAge"), BeanA.class));
assertFalse(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class));
}
@Test
public void testAnnotationOnMethodArgumentsWithFQN() throws SecurityException, NoSuchMethodException {
public void testAnnotationOnMethodArgumentsWithFQN() throws Exception {
String expression = "@args(*, test.annotation.EmptySpringAnnotation))";
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression);
assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class));
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class));
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class));
@@ -203,14 +226,16 @@ public class TigerAspectJExpressionPointcutTests {
}
@Test
public void testAnnotationOnMethodArgumentsWithWildcards() throws SecurityException, NoSuchMethodException {
public void testAnnotationOnMethodArgumentsWithWildcards() throws Exception {
String expression = "execution(* *(*, @(test..*) *))";
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression);
assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class));
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class));
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class));
@@ -260,12 +285,21 @@ public class TigerAspectJExpressionPointcutTests {
@EmptySpringAnnotation
public static class SpringAnnotated {
public void foo() {
}
}
static class BeanA {
interface IBeanA {
@Tx
int getAge();
}
static class BeanA implements IBeanA {
private String name;
private int age;
@@ -275,6 +309,7 @@ public class TigerAspectJExpressionPointcutTests {
}
@Tx
@Override
public int getAge() {
return age;
}
@@ -283,6 +318,7 @@ public class TigerAspectJExpressionPointcutTests {
@Tx
static class BeanB {
private String name;
public void setName(String name) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,7 +46,6 @@ import test.aop.PerTargetAspect;
import test.aop.TwoAdviceAspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.aop.framework.ProxyFactory;
@@ -82,22 +81,24 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Test
public void testRejectsPerCflowAspect() {
try {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(),"someBean"));
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(), "someBean"));
fail("Cannot accept cflow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().indexOf("PERCFLOW") != -1);
assertTrue(ex.getMessage().contains("PERCFLOW"));
}
}
@Test
public void testRejectsPerCflowBelowAspect() {
try {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(),"someBean"));
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(), "someBean"));
fail("Cannot accept cflowbelow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().indexOf("PERCFLOWBELOW") != -1);
assertTrue(ex.getMessage().contains("PERCFLOWBELOW"));
}
}
@@ -112,7 +113,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
Advised advised = (Advised) itb;
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[3];
LazySingletonAspectInstanceFactoryDecorator maaif =
@@ -199,7 +201,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length);
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
LazySingletonAspectInstanceFactoryDecorator maaif =
@@ -227,16 +230,15 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
int realAge = 65;
target.setAge(realAge);
PerTypeWithinAspectInstanceFactory aif = new PerTypeWithinAspectInstanceFactory();
TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(aif),
TestBean.class);
TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class);
assertEquals("No method calls", 0, aif.getInstantiationCount());
assertEquals("Around advice must now apply", 0, itb.getAge());
Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length);
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
LazySingletonAspectInstanceFactoryDecorator maaif =
@@ -257,9 +259,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
assertEquals("Around advice must still apply", 1, itb.getAge());
assertEquals("Around advice must still apply", 2, itb.getAge());
TestBean itb2 = (TestBean) createProxy(target,
getFixture().getAdvisors(aif),
TestBean.class);
TestBean itb2 = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class);
assertEquals(1, aif.getInstantiationCount());
assertEquals("Around advice be independent for second instance", 0, itb2.getAge());
assertEquals(2, aif.getInstantiationCount());
@@ -284,7 +284,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testNamedPointcutFromAspectLibraryWithBinding() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new NamedPointcutAspectFromLibraryWithBinding(),"someBean")),
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(
new NamedPointcutAspectFromLibraryWithBinding(), "someBean")),
ITestBean.class);
itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge());
@@ -296,7 +297,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
int realAge = 65;
target.setAge(realAge);
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance,"someBean")),
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, "someBean")),
ITestBean.class);
assertEquals("Around advice must apply", -1, itb.getAge());
assertEquals(realAge, target.getAge());
@@ -306,7 +307,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testBindingWithSingleArg() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(),"someBean")),
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(), "someBean")),
ITestBean.class);
itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge());
@@ -317,7 +319,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testBindingWithMultipleArgsDifferentlyOrdered() {
ManyValuedArgs target = new ManyValuedArgs();
ManyValuedArgs mva = (ManyValuedArgs) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ManyValuedArgs(),"someBean")),
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new ManyValuedArgs(), "someBean")),
ManyValuedArgs.class);
String a = "a";
@@ -338,7 +341,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
assertFalse(notLockableTarget instanceof Lockable);
NotLockable notLockable1 = (NotLockable) createProxy(notLockableTarget,
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")),
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
NotLockable.class);
assertTrue(notLockable1 instanceof Lockable);
Lockable lockable = (Lockable) notLockable1;
@@ -349,7 +352,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
NotLockable notLockable2Target = new NotLockable();
NotLockable notLockable2 = (NotLockable) createProxy(notLockable2Target,
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")),
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
NotLockable.class);
assertTrue(notLockable2 instanceof Lockable);
Lockable lockable2 = (Lockable) notLockable2;
@@ -368,11 +371,11 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Test
public void testIntroductionAdvisorExcludedFromTargetImplementingInterface() {
assertTrue(AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(
new MakeLockable(),"someBean")),
CannotBeUnlocked.class).isEmpty());
assertEquals(2, AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size());
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
CannotBeUnlocked.class).isEmpty());
assertEquals(2, AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size());
}
@Test
@@ -408,42 +411,34 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
List.class
),
CannotBeUnlocked.class);
List.class);
assertFalse("Type pattern must have excluded mixin", proxy instanceof Lockable);
}
/* prereq AspectJ 1.6.7
@Test
public void testIntroductionBasedOnAnnotationMatch_Spr5307() {
public void testIntroductionBasedOnAnnotationMatch_SPR5307() {
AnnotatedTarget target = new AnnotatedTargetImpl();
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeAnnotatedTypeModifiable(),"someBean"));
Object proxy = createProxy(target,
advisors,
AnnotatedTarget.class);
new SingletonMetadataAwareAspectInstanceFactory(new MakeAnnotatedTypeModifiable(), "someBean"));
Object proxy = createProxy(target, advisors, AnnotatedTarget.class);
System.out.println(advisors.get(1));
assertTrue(proxy instanceof Lockable);
Lockable lockable = (Lockable)proxy;
lockable.locked();
}
*/
// TODO: Why does this test fail? It hasn't been run before, so it maybe never actually passed...
@Test
@Ignore
public void testIntroductionWithArgumentBinding() {
TestBean target = new TestBean();
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeITestBeanModifiable(),"someBean"));
new SingletonMetadataAwareAspectInstanceFactory(new MakeITestBeanModifiable(), "someBean"));
advisors.addAll(getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")));
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")));
Modifiable modifiable = (Modifiable) createProxy(target,
advisors,
ITestBean.class);
Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class);
assertThat(modifiable, instanceOf(Modifiable.class));
Lockable lockable = (Lockable) modifiable;
assertFalse(lockable.locked());
@@ -477,11 +472,11 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testAspectMethodThrowsExceptionLegalOnSignature() {
TestBean target = new TestBean();
UnsupportedOperationException expectedException = new UnsupportedOperationException();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException),"someBean"));
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
try {
itb.getAge();
fail();
@@ -497,11 +492,11 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testAspectMethodThrowsExceptionIllegalOnSignature() {
TestBean target = new TestBean();
RemoteException expectedException = new RemoteException();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException),"someBean"));
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
try {
itb.getAge();
fail();
@@ -522,10 +517,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
// Required everywhere we use AspectJ proxies
pf.addAdvice(ExposeInvocationInterceptor.INSTANCE);
for (Object a : advisors) {
pf.addAdvisor((Advisor) a);
}
pf.addAdvisors(advisors);
pf.setExposeProxy(true);
return pf.getProxy();
@@ -534,13 +526,11 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Test
public void testTwoAdvicesOnOneAspect() {
TestBean target = new TestBean();
TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(twoAdviceAspect,"someBean"));
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(twoAdviceAspect, "someBean"));
assertEquals("Two advice methods found", 2, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
itb.setName("");
assertEquals(0, itb.getAge());
int newAge = 32;
@@ -551,16 +541,15 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Test
public void testAfterAdviceTypes() throws Exception {
Echo target = new Echo();
ExceptionHandling afterReturningAspect = new ExceptionHandling();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect,"someBean"));
Echo echo = (Echo) createProxy(target,
advisors,
Echo.class);
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect, "someBean"));
Echo echo = (Echo) createProxy(target, advisors, Echo.class);
assertEquals(0, afterReturningAspect.successCount);
assertEquals("", echo.echo(""));
assertEquals(1, afterReturningAspect.successCount);
assertEquals(0, afterReturningAspect.failureCount);
try {
echo.echo(new FileNotFoundException());
fail();
@@ -580,9 +569,9 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testFailureWithoutExplicitDeclarePrecedence() {
TestBean target = new TestBean();
MetadataAwareAspectInstanceFactory aspectInstanceFactory = new SingletonMetadataAwareAspectInstanceFactory(
new NoDeclarePrecedenceShouldFail(), "someBean");
new NoDeclarePrecedenceShouldFail(), "someBean");
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(aspectInstanceFactory), ITestBean.class);
getFixture().getAdvisors(aspectInstanceFactory), ITestBean.class);
itb.getAge();
}
@@ -590,21 +579,10 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
public void testDeclarePrecedenceNotSupported() {
TestBean target = new TestBean();
MetadataAwareAspectInstanceFactory aspectInstanceFactory = new SingletonMetadataAwareAspectInstanceFactory(
new DeclarePrecedenceShouldSucceed(), "someBean");
createProxy(target, getFixture().getAdvisors(aspectInstanceFactory),
ITestBean.class);
new DeclarePrecedenceShouldSucceed(), "someBean");
createProxy(target, getFixture().getAdvisors(aspectInstanceFactory), ITestBean.class);
}
/** Not supported in 2.0!
public void testExplicitDeclarePrecedencePreventsFailure() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new DeclarePrecedenceShouldSucceed(), "someBean")),
ITestBean.class);
assertEquals(666, itb.getAge());
}
*/
@Aspect("percflow(execution(* *(..)))")
public static class PerCflowAspect {
@@ -723,6 +701,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Aspect
public static class NamedPointcutAspectWithoutFQN {
@Pointcut("execution(* getAge())")
public void getAge() {
}
@@ -779,7 +758,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Around(value="setAge(age)",argNames="age")
// @ArgNames({"age"}) // AMC needs more work here? ignoring pjp arg... ok??
// argNames should be suported in Around as it is in Pointcut
// argNames should be suported in Around as it is in Pointcut
public void changeReturnType(ProceedingJoinPoint pjp, int age) throws Throwable {
pjp.proceed(new Object[] {age*2});
}
@@ -788,12 +767,12 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Aspect
public static class ManyValuedArgs {
public String mungeArgs(String a, int b, int c, String d, StringBuffer e) {
return a + b + c + d + e;
}
@Around(value="execution(String mungeArgs(..)) && args(a, b, c, d, e)",
argNames="b,c,d,e,a")
@Around(value="execution(String mungeArgs(..)) && args(a, b, c, d, e)", argNames="b,c,d,e,a")
public String reverseAdvice(ProceedingJoinPoint pjp, int b, int c, String d, StringBuffer e, String a) throws Throwable {
assertEquals(a + b+ c+ d+ e, pjp.proceed());
return a + b + c + d + e;
@@ -803,6 +782,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Aspect
public static class ExceptionAspect {
private final Exception ex;
public ExceptionAspect(Exception ex) {
@@ -829,8 +809,11 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Aspect
public static class ExceptionHandling {
public int successCount;
public int failureCount;
public int afterCount;
@AfterReturning("execution(* echo(*))")
@@ -902,10 +885,12 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
abstract class AbstractMakeModifiable {
public interface MutableModifable extends Modifiable {
void markDirty();
}
public static class ModifiableImpl implements MutableModifable {
private boolean modified;
@Override
@@ -924,10 +909,9 @@ abstract class AbstractMakeModifiable {
}
}
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)",
argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(JoinPoint jp,
MutableModifable mixin, Object newValue) {
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)", argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(
JoinPoint jp, MutableModifable mixin, Object newValue) {
/*
* We use the mixin to check and, if necessary, change,
@@ -992,6 +976,7 @@ class MakeITestBeanModifiable extends AbstractMakeModifiable {
}
/**
* Adds a declare parents pointcut - spr5307
* @author Andy Clement
@@ -1001,8 +986,7 @@ class MakeITestBeanModifiable extends AbstractMakeModifiable {
class MakeAnnotatedTypeModifiable extends AbstractMakeModifiable {
@DeclareParents(value = "(@org.springframework.aop.aspectj.annotation.Measured *)",
// @DeclareParents(value = "(@Measured *)", // this would be a nice alternative...
defaultImpl=DefaultLockable.class)
defaultImpl = DefaultLockable.class)
public static Lockable mixin;
}
@@ -1014,14 +998,11 @@ class MakeAnnotatedTypeModifiable extends AbstractMakeModifiable {
@Aspect
class MakeLockable {
@DeclareParents(value = "org.springframework..*",
defaultImpl=DefaultLockable.class)
@DeclareParents(value = "org.springframework..*", defaultImpl = DefaultLockable.class)
public static Lockable mixin;
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked(
Lockable mixin) // Bind to arg
{
public void checkNotLocked( Lockable mixin) {
// Can also obtain the mixin (this) this way
//Lockable mixin = (Lockable) jp.getThis();
if (mixin.locked()) {
@@ -1069,6 +1050,7 @@ interface Modifiable {
}
/**
* Used as a target.
* @author Andy Clement
@@ -1076,11 +1058,12 @@ interface Modifiable {
interface AnnotatedTarget {
}
@Measured
class AnnotatedTargetImpl implements AnnotatedTarget {
}
@Retention(RetentionPolicy.RUNTIME)
@interface Measured {}
@@ -1104,9 +1087,7 @@ class PerThisAspect {
public int count;
/**
* Just to check that this doesn't cause problems with introduction processing
*/
// Just to check that this doesn't cause problems with introduction processing
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Around("execution(int *.getAge())")
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,11 +41,12 @@ public class NameMatchMethodPointcutTests {
protected SerializableNopInterceptor nop;
/**
* Create an empty pointcut, populating instance variables.
*/
@Before
public void setUp() {
public void setup() {
ProxyFactory pf = new ProxyFactory(new SerializablePerson());
nop = new SerializableNopInterceptor();
pc = new NameMatchMethodPointcut();
@@ -53,6 +54,7 @@ public class NameMatchMethodPointcutTests {
proxied = (Person) pf.getProxy();
}
@Test
public void testMatchingOnly() {
// Can't do exact matching through isMatch
@@ -94,7 +96,7 @@ public class NameMatchMethodPointcutTests {
@Test
public void testSets() throws Throwable {
pc.setMappedNames(new String[] { "set*", "echo" });
pc.setMappedNames("set*", "echo");
assertEquals(0, nop.getCount());
proxied.getName();
proxied.setName("");
@@ -116,7 +118,7 @@ public class NameMatchMethodPointcutTests {
}
@Test
public void testEqualsAndHashCode() throws Exception {
public void testEqualsAndHashCode() {
NameMatchMethodPointcut pc1 = new NameMatchMethodPointcut();
NameMatchMethodPointcut pc2 = new NameMatchMethodPointcut();
@@ -70,13 +70,13 @@ public class HotSwappableTargetSourceTests {
@Test
public void testBasicFunctionality() {
SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable");
assertEquals(INITIAL_COUNT, proxied.getCount() );
assertEquals(INITIAL_COUNT, proxied.getCount());
proxied.doWork();
assertEquals(INITIAL_COUNT + 1, proxied.getCount() );
assertEquals(INITIAL_COUNT + 1, proxied.getCount());
proxied = (SideEffectBean) beanFactory.getBean("swappable");
proxied.doWork();
assertEquals(INITIAL_COUNT + 2, proxied.getCount() );
assertEquals(INITIAL_COUNT + 2, proxied.getCount());
}
@Test
@@ -85,9 +85,9 @@ public class HotSwappableTargetSourceTests {
SideEffectBean target2 = (SideEffectBean) beanFactory.getBean("target2");
SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable");
assertEquals(target1.getCount(), proxied.getCount() );
assertEquals(target1.getCount(), proxied.getCount());
proxied.doWork();
assertEquals(INITIAL_COUNT + 1, proxied.getCount() );
assertEquals(INITIAL_COUNT + 1, proxied.getCount());
HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
Object old = swapper.swap(target2);
@@ -56,14 +56,14 @@ public class PrototypeTargetSourceTests {
@Test
public void testPrototypeAndSingletonBehaveDifferently() {
SideEffectBean singleton = (SideEffectBean) beanFactory.getBean("singleton");
assertEquals(INITIAL_COUNT, singleton.getCount() );
assertEquals(INITIAL_COUNT, singleton.getCount());
singleton.doWork();
assertEquals(INITIAL_COUNT + 1, singleton.getCount() );
assertEquals(INITIAL_COUNT + 1, singleton.getCount());
SideEffectBean prototype = (SideEffectBean) beanFactory.getBean("prototype");
assertEquals(INITIAL_COUNT, prototype.getCount() );
assertEquals(INITIAL_COUNT, prototype.getCount());
prototype.doWork();
assertEquals(INITIAL_COUNT, prototype.getCount() );
assertEquals(INITIAL_COUNT, prototype.getCount());
}
@@ -62,9 +62,9 @@ public class ThreadLocalTargetSourceTests {
@Test
public void testUseDifferentManagedInstancesInSameThread() {
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, apartment.getCount() );
assertEquals(INITIAL_COUNT, apartment.getCount());
apartment.doWork();
assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
assertEquals(INITIAL_COUNT + 1, apartment.getCount());
ITestBean test = (ITestBean) beanFactory.getBean("threadLocal2");
assertEquals("Rod", test.getName());
@@ -74,12 +74,12 @@ public class ThreadLocalTargetSourceTests {
@Test
public void testReuseInSameThread() {
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, apartment.getCount() );
assertEquals(INITIAL_COUNT, apartment.getCount());
apartment.doWork();
assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
assertEquals(INITIAL_COUNT + 1, apartment.getCount());
apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
assertEquals(INITIAL_COUNT + 1, apartment.getCount());
}
/**
@@ -106,20 +106,20 @@ public class ThreadLocalTargetSourceTests {
@Test
public void testNewThreadHasOwnInstance() throws InterruptedException {
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, apartment.getCount() );
assertEquals(INITIAL_COUNT, apartment.getCount());
apartment.doWork();
apartment.doWork();
apartment.doWork();
assertEquals(INITIAL_COUNT + 3, apartment.getCount() );
assertEquals(INITIAL_COUNT + 3, apartment.getCount());
class Runner implements Runnable {
public SideEffectBean mine;
@Override
public void run() {
this.mine = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, mine.getCount() );
assertEquals(INITIAL_COUNT, mine.getCount());
mine.doWork();
assertEquals(INITIAL_COUNT + 1, mine.getCount() );
assertEquals(INITIAL_COUNT + 1, mine.getCount());
}
}
Runner r = new Runner();
@@ -130,11 +130,11 @@ public class ThreadLocalTargetSourceTests {
assertNotNull(r);
// Check it didn't affect the other thread's copy
assertEquals(INITIAL_COUNT + 3, apartment.getCount() );
assertEquals(INITIAL_COUNT + 3, apartment.getCount());
// When we use other thread's copy in this thread
// it should behave like ours
assertEquals(INITIAL_COUNT + 3, r.mine.getCount() );
assertEquals(INITIAL_COUNT + 3, r.mine.getCount());
// Bound to two threads
assertEquals(2, ((ThreadLocalTargetSourceStats) apartment).getObjectCount());
+2 -2
View File
@@ -80,8 +80,8 @@ compileTestJava {
dependencies {
aspects(project(":spring-orm"))
ajc("org.aspectj:aspectjtools:1.9.0") // for JDK 9+ build compatibility
rt("org.aspectj:aspectjrt:1.9.0") // for JDK 9+ build compatibility
ajc("org.aspectj:aspectjtools:1.9.1") // for JDK 9+ build compatibility
rt("org.aspectj:aspectjrt:1.9.1") // for JDK 9+ build compatibility
compile("org.aspectj:aspectjweaver:${aspectjVersion}") // for Maven POM exposure
optional(project(":spring-aop")) // for @Async support
optional(project(":spring-beans")) // for @Configurable support
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,6 +34,7 @@ import org.springframework.context.annotation.Role;
* @see org.springframework.cache.annotation.CachingConfigurationSelector
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class AspectJCachingConfiguration extends AbstractCachingConfiguration {
@Bean(name = CacheManagementConfigUtils.CACHE_ASPECT_BEAN_NAME)
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,6 +34,7 @@ import org.springframework.context.annotation.Role;
* @see org.springframework.cache.annotation.CachingConfigurationSelector
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class AspectJJCacheConfiguration extends AbstractJCacheConfiguration {
@Bean(name = CacheManagementConfigUtils.JCACHE_ASPECT_BEAN_NAME)
@@ -45,7 +45,7 @@ import org.springframework.transaction.annotation.AnnotationTransactionAttribute
* @see javax.transaction.Transactional
* @see AnnotationTransactionAspect
*/
@RequiredTypes({"javax.transaction.Transactional"})
@RequiredTypes("javax.transaction.Transactional")
public aspect JtaAnnotationTransactionAspect extends AbstractTransactionAspect {
public JtaAnnotationTransactionAspect() {
@@ -16,8 +16,8 @@
package org.springframework.beans;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -110,7 +110,7 @@ public abstract class AbstractPropertyAccessor extends TypeConverterSupport impl
}
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new LinkedList<>();
propertyAccessExceptions = new ArrayList<>();
}
propertyAccessExceptions.add(ex);
}
@@ -299,8 +299,7 @@ public class CachedIntrospectionResults {
// in particular for Java 8 default methods...
Class<?> clazz = beanClass;
while (clazz != null && clazz != Object.class) {
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<?> ifc : ifcs) {
for (Class<?> ifc : clazz.getInterfaces()) {
if (!ClassUtils.isJavaLanguageInterface(ifc)) {
for (PropertyDescriptor pd : getBeanInfo(ifc).getPropertyDescriptors()) {
if (!this.propertyDescriptorCache.containsKey(pd.getName())) {
@@ -43,8 +43,10 @@ import org.springframework.util.ObjectUtils;
* Decorator for a standard {@link BeanInfo} object, e.g. as created by
* {@link Introspector#getBeanInfo(Class)}, designed to discover and register static
* and/or non-void returning setter methods. For example:
*
* <pre class="code">
* public class Bean {
*
* private Foo foo;
*
* public Foo getFoo() {
@@ -56,6 +58,7 @@ import org.springframework.util.ObjectUtils;
* return this;
* }
* }</pre>
*
* The standard JavaBeans {@code Introspector} will discover the {@code getFoo} read
* method, but will bypass the {@code #setFoo(Foo)} write method, because its non-void
* returning signature does not comply with the JavaBeans specification.
@@ -68,6 +71,7 @@ import org.springframework.util.ObjectUtils;
* indexed properties</a> are fully supported.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @see #ExtendedBeanInfo(BeanInfo)
* @see ExtendedBeanInfoFactory
@@ -79,8 +83,7 @@ class ExtendedBeanInfo implements BeanInfo {
private final BeanInfo delegate;
private final Set<PropertyDescriptor> propertyDescriptors =
new TreeSet<>(new PropertyDescriptorComparator());
private final Set<PropertyDescriptor> propertyDescriptors = new TreeSet<>(new PropertyDescriptorComparator());
/**
@@ -91,11 +94,9 @@ class ExtendedBeanInfo implements BeanInfo {
* through its method descriptors to find any non-void returning write methods and
* update or create the corresponding {@link PropertyDescriptor} for each one found.
* @param delegate the wrapped {@code BeanInfo}, which is never modified
* @throws IntrospectionException if any problems occur creating and adding new
* property descriptors
* @see #getPropertyDescriptors()
*/
public ExtendedBeanInfo(BeanInfo delegate) throws IntrospectionException {
public ExtendedBeanInfo(BeanInfo delegate) {
this.delegate = delegate;
for (PropertyDescriptor pd : delegate.getPropertyDescriptors()) {
try {
@@ -213,9 +214,9 @@ class ExtendedBeanInfo implements BeanInfo {
/**
* Return the set of {@link PropertyDescriptor}s from the wrapped {@link BeanInfo}
* object as well as {@code PropertyDescriptor}s for each non-void returning setter
* method found during construction.
* Return the set of {@link PropertyDescriptor PropertyDescriptors} from the wrapped
* {@link BeanInfo} object as well as {@code PropertyDescriptors} for each non-void
* returning setter method found during construction.
* @see #ExtendedBeanInfo(BeanInfo)
*/
@Override
@@ -259,6 +260,9 @@ class ExtendedBeanInfo implements BeanInfo {
}
/**
* A simple {@link PropertyDescriptor}.
*/
static class SimplePropertyDescriptor extends PropertyDescriptor {
@Nullable
@@ -278,7 +282,9 @@ class ExtendedBeanInfo implements BeanInfo {
PropertyDescriptorUtils.copyNonMethodProperties(original, this);
}
public SimplePropertyDescriptor(String propertyName, @Nullable Method readMethod, Method writeMethod) throws IntrospectionException {
public SimplePropertyDescriptor(String propertyName, @Nullable Method readMethod, Method writeMethod)
throws IntrospectionException {
super(propertyName, null, null);
this.readMethod = readMethod;
this.writeMethod = writeMethod;
@@ -350,6 +356,9 @@ class ExtendedBeanInfo implements BeanInfo {
}
/**
* A simple {@link IndexedPropertyDescriptor}.
*/
static class SimpleIndexedPropertyDescriptor extends IndexedPropertyDescriptor {
@Nullable
@@ -379,8 +388,9 @@ class ExtendedBeanInfo implements BeanInfo {
PropertyDescriptorUtils.copyNonMethodProperties(original, this);
}
public SimpleIndexedPropertyDescriptor(String propertyName, @Nullable Method readMethod, @Nullable Method writeMethod,
@Nullable Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException {
public SimpleIndexedPropertyDescriptor(String propertyName, @Nullable Method readMethod,
@Nullable Method writeMethod, @Nullable Method indexedReadMethod, Method indexedWriteMethod)
throws IntrospectionException {
super(propertyName, null, null, null, null);
this.readMethod = readMethod;
@@ -27,7 +27,7 @@ import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Default implementation of the {@link PropertyValues} interface.
* The default implementation of the {@link PropertyValues} interface.
* Allows simple manipulation of properties, and provides constructors
* to support deep copy and construction from a Map.
*
@@ -80,7 +80,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
/**
* Construct a new MutablePropertyValues object from a Map.
* @param original Map with property values keyed by property name Strings
* @param original a Map with property values keyed by property name Strings
* @see #addPropertyValues(Map)
*/
public MutablePropertyValues(@Nullable Map<?, ?> original) {
@@ -101,7 +101,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
* PropertyValue objects as-is.
* <p>This is a constructor for advanced usage scenarios.
* It is not intended for typical programmatic use.
* @param propertyValueList List of PropertyValue objects
* @param propertyValueList a List of PropertyValue objects
*/
public MutablePropertyValues(@Nullable List<PropertyValue> propertyValueList) {
this.propertyValueList =
@@ -145,7 +145,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
/**
* Add all property values from the given Map.
* @param other Map with property values keyed by property name,
* @param other a Map with property values keyed by property name,
* which must be a String
* @return this in order to allow for adding multiple property values in a chain
*/
@@ -160,7 +160,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
/**
* Add a PropertyValue object, replacing any existing one for the
* corresponding property or getting merged with it (if applicable).
* @param pv PropertyValue object to add
* @param pv the PropertyValue object to add
* @return this in order to allow for adding multiple property values in a chain
*/
public MutablePropertyValues addPropertyValue(PropertyValue pv) {
@@ -348,14 +348,8 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MutablePropertyValues)) {
return false;
}
MutablePropertyValues that = (MutablePropertyValues) other;
return this.propertyValueList.equals(that.propertyValueList);
return (this == other || (other instanceof MutablePropertyValues &&
this.propertyValueList.equals(((MutablePropertyValues) other).propertyValueList)));
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,14 +30,12 @@ import org.springframework.util.ObjectUtils;
* @author Chris Beams
* @author Juergen Hoeller
*/
class PropertyDescriptorUtils {
abstract class PropertyDescriptorUtils {
/**
* See {@link java.beans.FeatureDescriptor}.
*/
public static void copyNonMethodProperties(PropertyDescriptor source, PropertyDescriptor target)
throws IntrospectionException {
public static void copyNonMethodProperties(PropertyDescriptor source, PropertyDescriptor target) {
target.setExpert(source.isExpert());
target.setHidden(source.isHidden());
target.setPreferred(source.isPreferred());
@@ -27,12 +27,12 @@ import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Currency;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -318,7 +318,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
// Check property-specific editor first.
PropertyEditor editor = getCustomEditor(propertyPath, requiredType);
if (editor == null) {
List<String> strippedPaths = new LinkedList<>();
List<String> strippedPaths = new ArrayList<>();
addStrippedPropertyPaths(strippedPaths, "", propertyPath);
for (Iterator<String> it = strippedPaths.iterator(); it.hasNext() && editor == null;) {
String strippedPath = it.next();
@@ -438,7 +438,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
if (this.customEditorsForPath != null) {
CustomEditorHolder editorHolder = this.customEditorsForPath.get(propertyName);
if (editorHolder == null) {
List<String> strippedPaths = new LinkedList<>();
List<String> strippedPaths = new ArrayList<>();
addStrippedPropertyPaths(strippedPaths, "", propertyName);
for (Iterator<String> it = strippedPaths.iterator(); it.hasNext() && editorHolder == null;) {
String strippedName = it.next();
@@ -517,7 +517,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* Holder for a registered custom editor with property name.
* Keeps the PropertyEditor itself plus the type it was registered for.
*/
private static class CustomEditorHolder {
private static final class CustomEditorHolder {
private final PropertyEditor propertyEditor;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,7 +46,7 @@ public interface PropertyValues {
* Return the changes since the previous PropertyValues.
* Subclasses should also override {@code equals}.
* @param old old property values
* @return PropertyValues updated or new properties.
* @return the updated or new properties.
* Return empty PropertyValues if there are no changes.
* @see Object#equals
*/
@@ -18,7 +18,7 @@ package org.springframework.beans.factory;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.FatalBeanException;
@@ -135,7 +135,7 @@ public class BeanCreationException extends FatalBeanException {
*/
public void addRelatedCause(Throwable ex) {
if (this.relatedCauses == null) {
this.relatedCauses = new LinkedList<>();
this.relatedCauses = new ArrayList<>();
}
this.relatedCauses.add(ex);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,7 +78,7 @@ public class BeanDefinitionStoreException extends FatalBeanException {
/**
* Create a new BeanDefinitionStoreException.
* @param resourceDescription description of the resource that the bean definition came from
* @param beanName the name of the bean requested
* @param beanName the name of the bean
* @param msg the detail message (appended to an introductory message that indicates
* the resource and the name of the bean)
*/
@@ -89,21 +89,23 @@ public class BeanDefinitionStoreException extends FatalBeanException {
/**
* Create a new BeanDefinitionStoreException.
* @param resourceDescription description of the resource that the bean definition came from
* @param beanName the name of the bean requested
* @param beanName the name of the bean
* @param msg the detail message (appended to an introductory message that indicates
* the resource and the name of the bean)
* @param cause the root cause (may be {@code null})
*/
public BeanDefinitionStoreException(@Nullable String resourceDescription, String beanName, String msg, @Nullable Throwable cause) {
super("Invalid bean definition with name '" + beanName + "' defined in " + resourceDescription + ": " + msg, cause);
public BeanDefinitionStoreException(
@Nullable String resourceDescription, String beanName, String msg, @Nullable Throwable cause) {
super("Invalid bean definition with name '" + beanName + "' defined in " + resourceDescription + ": " + msg,
cause);
this.resourceDescription = resourceDescription;
this.beanName = beanName;
}
/**
* Return the description of the resource that the bean
* definition came from, if any.
* Return the description of the resource that the bean definition came from, if available.
*/
@Nullable
public String getResourceDescription() {
@@ -111,7 +113,7 @@ public class BeanDefinitionStoreException extends FatalBeanException {
}
/**
* Return the name of the bean requested, if any.
* Return the name of the bean, if available.
*/
@Nullable
public String getBeanName() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,7 +32,6 @@ public class CannotLoadBeanClassException extends FatalBeanException {
@Nullable
private String resourceDescription;
@Nullable
private String beanName;
@Nullable
@@ -47,8 +46,8 @@ public class CannotLoadBeanClassException extends FatalBeanException {
* @param beanClassName the name of the bean class
* @param cause the root cause
*/
public CannotLoadBeanClassException(
@Nullable String resourceDescription, String beanName, @Nullable String beanClassName, ClassNotFoundException cause) {
public CannotLoadBeanClassException(@Nullable String resourceDescription, String beanName,
@Nullable String beanClassName, ClassNotFoundException cause) {
super("Cannot find class [" + beanClassName + "] for bean with name '" + beanName + "'" +
(resourceDescription != null ? " defined in " + resourceDescription : ""), cause);
@@ -65,8 +64,8 @@ public class CannotLoadBeanClassException extends FatalBeanException {
* @param beanClassName the name of the bean class
* @param cause the root cause
*/
public CannotLoadBeanClassException(
@Nullable String resourceDescription, String beanName, @Nullable String beanClassName, LinkageError cause) {
public CannotLoadBeanClassException(@Nullable String resourceDescription, String beanName,
@Nullable String beanClassName, LinkageError cause) {
super("Error loading class [" + beanClassName + "] for bean with name '" + beanName + "'" +
(resourceDescription != null ? " defined in " + resourceDescription : "") +
@@ -89,7 +88,6 @@ public class CannotLoadBeanClassException extends FatalBeanException {
/**
* Return the name of the bean requested.
*/
@Nullable
public String getBeanName() {
return this.beanName;
}
@@ -28,7 +28,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -245,10 +244,10 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
ReflectionUtils.doWithMethods(beanClass, method -> {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
Assert.state(beanFactory != null, "No BeanFactory available");
Assert.state(this.beanFactory != null, "No BeanFactory available");
LookupOverride override = new LookupOverride(method, lookup.value());
try {
RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName);
RootBeanDefinition mbd = (RootBeanDefinition) this.beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -424,11 +423,11 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
}
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
ReflectionUtils.doWithLocalFields(targetClass, field -> {
AnnotationAttributes ann = findAutowiredAnnotation(field);
@@ -541,7 +540,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
private Object resolvedCachedArgument(@Nullable String beanName, @Nullable Object cachedArgument) {
if (cachedArgument instanceof DependencyDescriptor) {
DependencyDescriptor descriptor = (DependencyDescriptor) cachedArgument;
Assert.state(beanFactory != null, "No BeanFactory available");
Assert.state(this.beanFactory != null, "No BeanFactory available");
return this.beanFactory.resolveDependency(descriptor, beanName, null, null);
}
else {
@@ -23,9 +23,10 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -196,23 +197,23 @@ public class InitDestroyAnnotationBeanPostProcessor
private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
final boolean debug = logger.isDebugEnabled();
LinkedList<LifecycleElement> initMethods = new LinkedList<>();
LinkedList<LifecycleElement> destroyMethods = new LinkedList<>();
List<LifecycleElement> initMethods = new ArrayList<>();
List<LifecycleElement> destroyMethods = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final LinkedList<LifecycleElement> currInitMethods = new LinkedList<>();
final LinkedList<LifecycleElement> currDestroyMethods = new LinkedList<>();
final List<LifecycleElement> currInitMethods = new ArrayList<>();
final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
if (initAnnotationType != null && method.isAnnotationPresent(initAnnotationType)) {
if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
LifecycleElement element = new LifecycleElement(method);
currInitMethods.add(element);
if (debug) {
logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
}
}
if (destroyAnnotationType != null && method.isAnnotationPresent(destroyAnnotationType)) {
if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
currDestroyMethods.add(new LifecycleElement(method));
if (debug) {
logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,8 +56,8 @@ import org.springframework.util.Assert;
* and obviates the need (<b>in part</b>) for a developer to code a method that
* simply checks that all required properties have actually been set.
*
* <p>Please note that an 'init' method may still need to implemented (and may
* still be desirable), because all that this class does is enforce that a
* <p>Please note that an 'init' method may still need to be implemented (and may
* still be desirable), because all that this class does is enforcing that a
* 'required' property has actually been configured with a value. It does
* <b>not</b> check anything else... In particular, it does not check that a
* configured value is not {@code null}.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -225,7 +225,7 @@ public abstract class AbstractFactoryBean<T>
* FactoryBean is supposed to implement, for use with an 'early singleton
* proxy' that will be exposed in case of a circular reference.
* <p>The default implementation returns this FactoryBean's object type,
* provided that it is an interface, or {@code null} else. The latter
* provided that it is an interface, or {@code null} otherwise. The latter
* indicates that early singleton access is not supported by this FactoryBean.
* This will lead to a FactoryBeanNotInitializedException getting thrown.
* @return the interfaces to use for 'early singletons',
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -89,7 +89,9 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single
void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);
/**
* Return this factory's class loader for loading bean classes.
* Return this factory's class loader for loading bean classes
* (only {@code null} if even the system ClassLoader isn't accessible).
* @see org.springframework.util.ClassUtils#forName(String, ClassLoader)
*/
@Nullable
ClassLoader getBeanClassLoader();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.beans.factory.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -45,7 +45,7 @@ public class ConstructorArgumentValues {
private final Map<Integer, ValueHolder> indexedArgumentValues = new LinkedHashMap<>(0);
private final List<ValueHolder> genericArgumentValues = new LinkedList<>();
private final List<ValueHolder> genericArgumentValues = new ArrayList<>();
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -352,7 +352,6 @@ public class DependencyDescriptor extends InjectionPoint implements Serializable
Type[] args = ((ParameterizedType) type).getActualTypeArguments();
type = args[args.length - 1];
}
// TODO: Object.class if unresolvable
}
if (type instanceof Class) {
return (Class<?>) type;
@@ -202,7 +202,7 @@ public class FieldRetrievingFactoryBean
}
// Try to get the exact method first.
Class<?> targetClass = (this.targetObject != null) ? this.targetObject.getClass() : this.targetClass;
Class<?> targetClass = (this.targetObject != null ? this.targetObject.getClass() : this.targetClass);
this.fieldObject = targetClass.getField(this.targetField);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
* {@link #postProcessAfterInitialization} callback from the configured
* {@link BeanPostProcessor BeanPostProcessors}.
* <p>This callback will only be applied to bean definitions with a bean class.
* In particular, it will not be applied to beans with a "factory-method".
* In particular, it will not be applied to beans with a factory method.
* <p>Post-processors may implement the extended
* {@link SmartInstantiationAwareBeanPostProcessor} interface in order
* to predict the type of the bean object that they are going to return here.
@@ -65,8 +65,8 @@ public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
* @return the bean object to expose instead of a default instance of the target bean,
* or {@code null} to proceed with default instantiation
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessAfterInstantiation
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#hasBeanClass
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName
*/
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
@@ -86,6 +86,7 @@ public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
* Returning {@code false} will also prevent any subsequent InstantiationAwareBeanPostProcessor
* instances being invoked on this bean instance.
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessBeforeInstantiation
*/
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
@@ -104,9 +105,8 @@ public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
* dependency types - which the factory handles specifically - already filtered out)
* @param bean the bean instance created, but whose properties have not yet been set
* @param beanName the name of the bean
* @return the actual property values to apply to the given bean
* (can be the passed-in PropertyValues instance), or {@code null}
* to skip property population
* @return the actual property values to apply to the given bean (can be the passed-in
* PropertyValues instance), or {@code null} to skip property population
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.MutablePropertyValues
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,7 @@ public abstract class InstantiationAwareBeanPostProcessorAdapter implements Smar
@Override
@Nullable
public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
public Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -64,6 +64,8 @@ import org.springframework.lang.Nullable;
* Note that the value of "foo" in the first document is not simply replaced
* with the value in the second, but its nested values are merged.
*
* <p>Requires SnakeYAML 1.18 or higher, as of Spring Framework 5.0.6.
*
* @author Dave Syer
* @author Juergen Hoeller
* @since 4.1
@@ -30,6 +30,7 @@ import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
@@ -45,6 +46,8 @@ import org.springframework.util.StringUtils;
/**
* Base class for YAML factories.
*
* <p>Requires SnakeYAML 1.18 or higher, as of Spring Framework 5.0.6.
*
* @author Dave Syer
* @author Juergen Hoeller
* @since 4.1
@@ -77,15 +80,16 @@ public abstract class YamlProcessor {
* name: My Cool App
* </pre>
* when mapped with
* <code>documentMatchers = YamlProcessor.mapMatcher({"environment": "prod"})</code>
* <pre class="code">
* setDocumentMatchers(properties ->
* ("prod".equals(properties.getProperty("environment")) ? MatchStatus.FOUND : MatchStatus.NOT_FOUND));
* </pre>
* would end up as
* <pre class="code">
* environment=prod
* url=http://foo.bar.com
* name=My Cool App
* url=http://dev.bar.com
* </pre>
* @param matchers a map of keys to value patterns (regular expressions)
*/
public void setDocumentMatchers(DocumentMatcher... matchers) {
this.documentMatchers = Arrays.asList(matchers);
@@ -94,8 +98,7 @@ public abstract class YamlProcessor {
/**
* Flag indicating that a document for which all the
* {@link #setDocumentMatchers(DocumentMatcher...) document matchers} abstain will
* nevertheless match.
* @param matchDefault the flag to set (default true)
* nevertheless match. Default is {@code true}.
*/
public void setMatchDefault(boolean matchDefault) {
this.matchDefault = matchDefault;
@@ -104,9 +107,7 @@ public abstract class YamlProcessor {
/**
* Method to use for resolving resources. Each resource will be converted to a Map,
* so this property is used to decide which map entries to keep in the final output
* from this factory.
* @param resolutionMethod the resolution method to set (defaults to
* {@link ResolutionMethod#OVERRIDE}).
* from this factory. Default is {@link ResolutionMethod#OVERRIDE}.
*/
public void setResolutionMethod(ResolutionMethod resolutionMethod) {
Assert.notNull(resolutionMethod, "ResolutionMethod must not be null");
@@ -144,9 +145,14 @@ public abstract class YamlProcessor {
/**
* Create the {@link Yaml} instance to use.
* <p>The default implementation sets the "allowDuplicateKeys" flag to {@code false},
* enabling built-in duplicate key handling in SnakeYAML 1.18+.
* @see LoaderOptions#setAllowDuplicateKeys(boolean)
*/
protected Yaml createYaml() {
return new Yaml(new StrictMapAppenderConstructor());
LoaderOptions options = new LoaderOptions();
options.setAllowDuplicateKeys(false);
return new Yaml(options);
}
private boolean process(MatchCallback callback, Yaml yaml, Resource resource) {
@@ -293,10 +299,15 @@ public abstract class YamlProcessor {
// Need a compound key
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) value;
int count = 0;
for (Object object : collection) {
buildFlattenedMap(result,
Collections.singletonMap("[" + (count++) + "]", object), key);
if (collection.isEmpty()) {
result.put(key, "");
}
else {
int count = 0;
for (Object object : collection) {
buildFlattenedMap(result, Collections.singletonMap(
"[" + (count++) + "]", object), key);
}
}
}
else {
@@ -389,7 +400,10 @@ public abstract class YamlProcessor {
/**
* A specialized {@link Constructor} that checks for duplicate keys.
* @deprecated as of Spring Framework 5.0.6 (not used anymore here),
* superseded by SnakeYAML's own duplicate key handling
*/
@Deprecated
protected static class StrictMapAppenderConstructor extends Constructor {
// Declared as public for use in subclasses
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,6 +74,8 @@ import org.springframework.lang.Nullable;
* servers[1]=foo.bar.com
* </pre>
*
* <p>Requires SnakeYAML 1.18 or higher, as of Spring Framework 5.0.6.
*
* @author Dave Syer
* @author Stephane Nicoll
* @author Juergen Hoeller
@@ -371,9 +371,9 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
}
else if ("ref".equals(name)) {
String refName;
if (args[0] == null)
if (args[0] == null) {
throw new IllegalArgumentException("Argument to ref() is not a valid bean or was not found");
}
if (args[0] instanceof RuntimeBeanReference) {
refName = ((RuntimeBeanReference) args[0]).getBeanName();
}
@@ -489,11 +489,11 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
Map.Entry factoryBeanEntry = (Map.Entry) ((Map) args[0]).entrySet().iterator().next();
// If we have a closure body, that will be the last argument.
// In between are the constructor args
int constructorArgsTest = hasClosureArgument?2:1;
int constructorArgsTest = (hasClosureArgument ? 2 : 1);
// If we have more than this number of args, we have constructor args
if (args.length > constructorArgsTest){
// factory-method requires args
int endOfConstructArgs = (hasClosureArgument? args.length - 1 : args.length);
int endOfConstructArgs = (hasClosureArgument ? args.length - 1 : args.length);
this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName, null,
resolveConstructorArguments(args, 1, endOfConstructArgs));
}
@@ -511,7 +511,7 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
}
else {
List constructorArgs = resolveConstructorArguments(args, 0, hasClosureArgument ? args.length - 1 : args.length);
currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName, null, constructorArgs);
this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName, null, constructorArgs);
}
if (hasClosureArgument) {
@@ -545,8 +545,8 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
}
/**
* Checks whether there are any {@link RuntimeBeanReference}s inside the {@link Map}
* and converts it to a {@link ManagedMap} if necessary.
* Checks whether there are any {@link RuntimeBeanReference RuntimeBeanReferences}
* inside the {@link Map} and converts it to a {@link ManagedMap} if necessary.
* @param map the original Map
* @return either the original map or a managed copy of it
*/
@@ -567,8 +567,8 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
}
/**
* Checks whether there are any {@link RuntimeBeanReference}s inside the {@link List}
* and converts it to a {@link ManagedList} if necessary.
* Checks whether there are any {@link RuntimeBeanReference RuntimeBeanReferences}
* inside the {@link List} and converts it to a {@link ManagedList} if necessary.
* @param list the original List
* @return either the original list or a managed copy of it
*/
@@ -630,7 +630,7 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
/**
* This method overrides property retrieval in the scope of the
* {@code GroovyBeanDefinitionReader} to either:
* {@code GroovyBeanDefinitionReader}. A property retrieval will either:
* <ul>
* <li>Retrieve a variable from the bean builder's binding if it exists
* <li>Retrieve a RuntimeBeanReference for a specific bean if it exists
@@ -16,7 +16,7 @@
package org.springframework.beans.factory.parsing;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
import org.springframework.lang.Nullable;
@@ -38,7 +38,7 @@ public class CompositeComponentDefinition extends AbstractComponentDefinition {
@Nullable
private final Object source;
private final List<ComponentDefinition> nestedComponents = new LinkedList<>();
private final List<ComponentDefinition> nestedComponents = new ArrayList<>();
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -82,7 +82,7 @@ public final class ParseState {
*/
@Nullable
public Entry peek() {
return this.state.isEmpty() ? null : this.state.peek();
return this.state.peek();
}
/**
@@ -30,15 +30,15 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
@@ -155,7 +155,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");
/** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */
private final Map<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>(16);
private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>(16);
/** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */
private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
@@ -298,8 +298,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
RootBeanDefinition bd = new RootBeanDefinition(beanClass);
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
// For the nullability warning, see the elaboration in AbstractBeanFactory.doGetBean;
// in short: This is never going to be null unless user-declared code enforces null.
return (T) createBean(beanClass.getName(), bd, null);
}
@@ -333,8 +331,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
populateBean(beanName, bd, bw);
// For the nullability warning, see the elaboration in AbstractBeanFactory.doGetBean;
// in short: This is never going to be null unless user-declared code enforces null.
return initializeBean(beanName, existingBean, bd);
}
@@ -354,8 +350,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
// For the nullability warning, see the elaboration in AbstractBeanFactory.doGetBean;
// in short: This is never going to be null unless user-declared code enforces null.
return createBean(beanClass.getName(), bd, null);
}
@@ -722,19 +716,18 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
int minNrOfArgs =
(mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0);
Method[] candidates = ReflectionUtils.getUniqueDeclaredMethods(factoryClass);
for (Method factoryMethod : candidates) {
if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
factoryMethod.getName().equals(mbd.getFactoryMethodName()) &&
factoryMethod.getParameterCount() >= minNrOfArgs) {
for (Method candidate : candidates) {
if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) &&
candidate.getParameterCount() >= minNrOfArgs) {
// Declared type variables to inspect?
if (factoryMethod.getTypeParameters().length > 0) {
if (candidate.getTypeParameters().length > 0) {
try {
// Fully resolve parameter names and argument values.
Class<?>[] paramTypes = factoryMethod.getParameterTypes();
Class<?>[] paramTypes = candidate.getParameterTypes();
String[] paramNames = null;
ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
if (pnd != null) {
paramNames = pnd.getParameterNames(factoryMethod);
paramNames = pnd.getParameterNames(candidate);
}
ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
@@ -751,8 +744,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
}
Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(
factoryMethod, args, getBeanClassLoader());
uniqueCandidate = (commonType == null ? factoryMethod : null);
candidate, args, getBeanClassLoader());
uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ?
candidate : null);
commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
if (commonType == null) {
// Ambiguous return types found: return null to indicate "not determinable".
@@ -766,8 +760,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
}
else {
uniqueCandidate = (commonType == null ? factoryMethod : null);
commonType = ClassUtils.determineCommonAncestor(factoryMethod.getReturnType(), commonType);
uniqueCandidate = (commonType == null ? candidate : null);
commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType);
if (commonType == null) {
// Ambiguous return types found: return null to indicate "not determinable".
return null;
@@ -776,12 +770,15 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
}
if (commonType != null) {
// Clear return type found: all factory methods return same type.
mbd.factoryMethodReturnType = (uniqueCandidate != null ?
ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType));
if (commonType == null) {
return null;
}
return commonType;
// Common return type found: all factory methods return same type. For a non-parameterized
// unique candidate, cache the full type declaration context of the target factory method.
cachedReturnType = (uniqueCandidate != null ?
ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType));
mbd.factoryMethodReturnType = cachedReturnType;
return cachedReturnType.resolve();
}
/**
@@ -1275,7 +1272,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* from the bean definition.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param bw BeanWrapper with bean instance
* @param bw the BeanWrapper with bean instance
*/
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
@@ -1364,7 +1361,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* @param beanName the name of the bean we're wiring up.
* Useful for debugging messages; not used functionally.
* @param mbd bean definition to update through autowiring
* @param bw BeanWrapper from which we can obtain information about the bean
* @param bw the BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByName(
@@ -1398,7 +1395,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* behavior for bigger applications.
* @param beanName the name of the bean to autowire by type
* @param mbd the merged bean definition to update through autowiring
* @param bw BeanWrapper from which we can obtain information about the bean
* @param bw the BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByType(
@@ -1496,7 +1493,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* @see #isExcludedFromDependencyCheck
*/
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) {
List<PropertyDescriptor> pds = new LinkedList<>(Arrays.asList(bw.getPropertyDescriptors()));
List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors()));
pds.removeIf(this::isExcludedFromDependencyCheck);
return pds.toArray(new PropertyDescriptor[0]);
}
@@ -1866,6 +1863,14 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
}
/**
* Expose the logger to collaborating delegates.
* @since 5.0.7
*/
Log getLogger() {
return logger;
}
/**
* Special DependencyDescriptor variant for Spring's good old autowire="byType" mode.
@@ -1501,7 +1501,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* should be used as fallback.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @return the type for the bean if determinable, or {@code null} else
* @return the type for the bean if determinable, or {@code null} otherwise
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,6 +55,7 @@ public interface BeanDefinitionRegistry extends AliasRegistry {
* @throws BeanDefinitionStoreException if the BeanDefinition is invalid
* or if there is already a BeanDefinition for the specified bean name
* (and we are not allowed to override it)
* @see GenericBeanDefinition
* @see RootBeanDefinition
* @see ChildBeanDefinition
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -80,10 +80,9 @@ class BeanDefinitionResource extends AbstractResource {
* This implementation compares the underlying BeanDefinition.
*/
@Override
public boolean equals(Object obj) {
return (obj == this ||
(obj instanceof BeanDefinitionResource &&
((BeanDefinitionResource) obj).beanDefinition.equals(this.beanDefinition)));
public boolean equals(Object other) {
return (this == other || (other instanceof BeanDefinitionResource &&
((BeanDefinitionResource) other).beanDefinition.equals(this.beanDefinition)));
}
/**
@@ -32,6 +32,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
@@ -78,6 +80,8 @@ class ConstructorResolver {
private final AbstractAutowireCapableBeanFactory beanFactory;
private final Log logger;
/**
* Create a new ConstructorResolver for the given factory and instantiation strategy.
@@ -85,6 +89,7 @@ class ConstructorResolver {
*/
public ConstructorResolver(AbstractAutowireCapableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
this.logger = beanFactory.getLogger();
}
@@ -193,9 +198,8 @@ class ConstructorResolver {
getUserDeclaredConstructor(candidate), autowiring);
}
catch (UnsatisfiedDependencyException ex) {
if (this.beanFactory.logger.isTraceEnabled()) {
this.beanFactory.logger.trace(
"Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
if (logger.isTraceEnabled()) {
logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
if (causes == null) {
@@ -471,9 +475,8 @@ class ConstructorResolver {
beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring);
}
catch (UnsatisfiedDependencyException ex) {
if (this.beanFactory.logger.isTraceEnabled()) {
this.beanFactory.logger.trace("Ignoring factory method [" + candidate +
"] of bean '" + beanName + "': " + ex);
if (logger.isTraceEnabled()) {
logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next overloaded factory method.
if (causes == null) {
@@ -733,8 +736,8 @@ class ConstructorResolver {
for (String autowiredBeanName : autowiredBeanNames) {
this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
if (this.beanFactory.logger.isDebugEnabled()) {
this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName +
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName +
"' via " + (executable instanceof Constructor ? "constructor" : "factory method") +
" to bean named '" + autowiredBeanName + "'");
}
@@ -79,19 +79,17 @@ import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Default implementation of the
* {@link org.springframework.beans.factory.ListableBeanFactory} and
* {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory
* based on bean definition objects.
* Spring's default implementation of the {@link ConfigurableListableBeanFactory}
* and {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory
* based on bean definition metadata, extensible through post-processors.
*
* <p>Typical usage is registering all bean definitions first (possibly read
* from a bean definition file), before accessing beans. Bean definition lookup
* from a bean definition file), before accessing beans. Bean lookup by name
* is therefore an inexpensive operation in a local bean definition table,
* operating on pre-built bean definition metadata objects.
* operating on pre-resolved bean definition metadata objects.
*
* <p>Can be used as a standalone bean factory, or as a superclass for custom
* bean factories. Note that readers for specific bean definition formats are
* typically implemented separately rather than as bean factory subclasses:
* <p>Note that readers for specific bean definition formats are typically
* implemented separately rather than as bean factory subclasses:
* see for example {@link PropertiesBeanDefinitionReader} and
* {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}.
*
@@ -108,9 +106,10 @@ import org.springframework.util.StringUtils;
* @author Phillip Webb
* @author Stephane Nicoll
* @since 16 April 2001
* @see StaticListableBeanFactory
* @see PropertiesBeanDefinitionReader
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see #registerBeanDefinition
* @see #addBeanPostProcessor
* @see #getBean
* @see #resolveDependency
*/
@SuppressWarnings("serial")
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
@@ -439,9 +438,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (allowEagerInit) {
throw ex;
}
// Probably contains a placeholder: let's ignore it for type matching purposes.
if (this.logger.isDebugEnabled()) {
this.logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
// Probably a class name with a placeholder: let's ignore it for type matching purposes.
if (logger.isDebugEnabled()) {
logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
}
onSuppressedException(ex);
}
@@ -449,9 +448,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (allowEagerInit) {
throw ex;
}
// Probably contains a placeholder: let's ignore it for type matching purposes.
if (this.logger.isDebugEnabled()) {
this.logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
// Probably some metadata with a placeholder: let's ignore it for type matching purposes.
if (logger.isDebugEnabled()) {
logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
}
onSuppressedException(ex);
}
@@ -521,8 +520,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
BeanCreationException bce = (BeanCreationException) rootCause;
String exBeanName = bce.getBeanName();
if (exBeanName != null && isCurrentlyInCreation(exBeanName)) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Ignoring match to currently created bean '" + exBeanName + "': " +
if (logger.isDebugEnabled()) {
logger.debug("Ignoring match to currently created bean '" + exBeanName + "': " +
ex.getMessage());
}
onSuppressedException(ex);
@@ -680,8 +679,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("No bean named '" + beanName + "' found in " + this);
if (logger.isTraceEnabled()) {
logger.trace("No bean named '" + beanName + "' found in " + this);
}
throw new NoSuchBeanDefinitionException(beanName);
}
@@ -725,8 +724,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
@Override
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Pre-instantiating singletons in " + this);
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
@@ -802,34 +801,32 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
BeanDefinition oldBeanDefinition;
oldBeanDefinition = this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition != null) {
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
"': There is already [" + existingDefinition + "] bound.");
}
else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (this.logger.isWarnEnabled()) {
this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
if (logger.isWarnEnabled()) {
logger.warn("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
oldBeanDefinition + "] with [" + beanDefinition + "]");
existingDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(oldBeanDefinition)) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + oldBeanDefinition +
else if (!beanDefinition.equals(existingDefinition)) {
if (logger.isInfoEnabled()) {
logger.info("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + oldBeanDefinition +
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
@@ -860,7 +857,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
this.frozenBeanDefinitionNames = null;
}
if (oldBeanDefinition != null || containsSingleton(beanName)) {
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
@@ -871,8 +868,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
BeanDefinition bd = this.beanDefinitionMap.remove(beanName);
if (bd == null) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("No bean named '" + beanName + "' found in " + this);
if (logger.isTraceEnabled()) {
logger.trace("No bean named '" + beanName + "' found in " + this);
}
throw new NoSuchBeanDefinitionException(beanName);
}
@@ -1251,7 +1248,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
private FactoryAwareOrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, Object> beans) {
private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, Object> beans) {
IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>();
beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName));
return new FactoryAwareOrderSourceProvider(instancesToBeanNames);
@@ -1521,8 +1518,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
// Probably a proxy interfering with target type match -> throw meaningful exception.
Object beanInstance = getSingleton(beanName, false);
Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class) ?
beanInstance.getClass() : predictBeanType(beanName, mbd);
Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ?
beanInstance.getClass() : predictBeanType(beanName, mbd));
if (beanType != null && !type.isAssignableFrom(beanType)) {
throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
}
@@ -1618,6 +1615,29 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
/**
* A dependency descriptor marker for nested elements.
*/
private static class NestedDependencyDescriptor extends DependencyDescriptor {
public NestedDependencyDescriptor(DependencyDescriptor original) {
super(original);
increaseNestingLevel();
}
}
/**
* A dependency descriptor marker for multiple elements.
*/
private static class MultiElementDescriptor extends NestedDependencyDescriptor {
public MultiElementDescriptor(DependencyDescriptor original) {
super(original);
}
}
/**
* Serializable ObjectFactory/ObjectProvider for lazy resolution of a dependency.
*/
@@ -1656,7 +1676,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return createOptionalDependency(this.descriptor, this.beanName, args);
}
else {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) {
@Override
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) {
return beanFactory.getBean(beanName, args);
@@ -1677,7 +1697,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return createOptionalDependency(this.descriptor, this.beanName);
}
else {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) {
@Override
public boolean isRequired() {
return false;
@@ -1690,7 +1710,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
@Override
@Nullable
public Object getIfUnique() throws BeansException {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(descriptor) {
DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) {
@Override
public boolean isRequired() {
return false;
@@ -1722,7 +1742,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
/**
* Serializable ObjectFactory for lazy resolution of a dependency.
* A {@code javax.inject.Provider} implementation for lazy resolution of a dependency.
*/
private class Jsr330DependencyProvider extends DependencyObjectProvider implements Provider<Object> {
@@ -1795,21 +1815,4 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
private static class NestedDependencyDescriptor extends DependencyDescriptor {
public NestedDependencyDescriptor(DependencyDescriptor original) {
super(original);
increaseNestingLevel();
}
}
private static class MultiElementDescriptor extends NestedDependencyDescriptor {
public MultiElementDescriptor(DependencyDescriptor original) {
super(original);
}
}
}
@@ -26,9 +26,6 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
@@ -73,9 +70,6 @@ import org.springframework.util.StringUtils;
*/
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -248,12 +248,12 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((DisposableBean) bean).destroy();
((DisposableBean) this.bean).destroy();
return null;
}, acc);
}, this.acc);
}
else {
((DisposableBean) bean).destroy();
((DisposableBean) this.bean).destroy();
}
}
catch (Throwable ex) {
@@ -326,7 +326,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
destroyMethod.invoke(bean, args), acc);
destroyMethod.invoke(this.bean, args), this.acc);
}
catch (PrivilegedActionException pax) {
throw (InvocationTargetException) pax.getException();
@@ -334,12 +334,12 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
}
else {
ReflectionUtils.makeAccessible(destroyMethod);
destroyMethod.invoke(bean, args);
destroyMethod.invoke(this.bean, args);
}
}
catch (InvocationTargetException ex) {
String msg = "Invocation of destroy method '" + this.destroyMethodName +
"' failed on bean with name '" + this.beanName + "'";
String msg = "Destroy method '" + this.destroyMethodName + "' on bean with name '" +
this.beanName + "' threw an exception";
if (logger.isDebugEnabled()) {
logger.warn(msg, ex.getTargetException());
}
@@ -348,7 +348,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
}
}
catch (Throwable ex) {
logger.error("Couldn't invoke destroy method '" + this.destroyMethodName +
logger.error("Failed to invoke destroy method '" + this.destroyMethodName +
"' on bean with name '" + this.beanName + "'", ex);
}
}
@@ -107,6 +107,11 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
beforeSingletonCreation(beanName);
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
@@ -114,6 +119,9 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
@@ -900,9 +900,9 @@ public class BeanDefinitionParserDelegate {
*/
@Nullable
public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
String elementName = (propertyName != null ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element");
// Should only have one child element: ref, value, list, etc.
NodeList nl = ele.getChildNodes();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ public abstract class AbstractPropertyValuesTests {
/**
* Must contain: forname=Tony surname=Blair age=50
*/
protected void doTestTony(PropertyValues pvs) throws Exception {
protected void doTestTony(PropertyValues pvs) {
assertTrue("Contains 3", pvs.getPropertyValues().length == 3);
assertTrue("Contains forname", pvs.contains("forname"));
assertTrue("Contains surname", pvs.contains("surname"));
@@ -52,4 +52,4 @@ public abstract class AbstractPropertyValuesTests {
assertTrue("Map size is 0", m.size() == 0);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +29,7 @@ import static org.junit.Assert.*;
public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
@Test
public void testValid() throws Exception {
public void testValid() {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
@@ -44,7 +44,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
}
@Test
public void testAddOrOverride() throws Exception {
public void testAddOrOverride() {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
@@ -59,7 +59,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
}
@Test
public void testChangesOnEquals() throws Exception {
public void testChangesOnEquals() {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
@@ -70,7 +70,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
}
@Test
public void testChangeOfOneField() throws Exception {
public void testChangeOfOneField() {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
@@ -1567,6 +1567,7 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd1 = createConstructorDependencyBeanDefinition(99);
parent.registerBeanDefinition("bd1", bd1);
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent);
ConstructorDependency bean = lbf.getBean(ConstructorDependency.class, 42);
assertThat(bean.beanName, equalTo("bd1"));
assertThat(bean.spouseAge, equalTo(42));
@@ -1579,7 +1580,6 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd2 = new RootBeanDefinition(ConstructorDependency.class);
bd2.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bd2.getConstructorArgumentValues().addGenericArgumentValue("43");
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2);
@@ -1595,6 +1595,7 @@ public class DefaultListableBeanFactoryTests {
bd2.setPrimary(true);
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2);
ConstructorDependency bean = lbf.getBean(ConstructorDependency.class, 42);
assertThat(bean.beanName, equalTo("bd2"));
assertThat(bean.spouseAge, equalTo(42));
@@ -1607,9 +1608,9 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd2 = createConstructorDependencyBeanDefinition(43);
bd1.setPrimary(true);
bd2.setPrimary(true);
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2);
thrown.expect(NoUniqueBeanDefinitionException.class);
thrown.expectMessage(containsString("more than one 'primary'"));
lbf.getBean(ConstructorDependency.class, 42);
@@ -1661,7 +1662,7 @@ public class DefaultListableBeanFactoryTests {
private RootBeanDefinition createConstructorDependencyBeanDefinition(int age) {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependency.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bd.getConstructorArgumentValues().addGenericArgumentValue(String.valueOf(age));
bd.getConstructorArgumentValues().addGenericArgumentValue(age);
return bd;
}
@@ -2383,7 +2384,7 @@ public class DefaultListableBeanFactoryTests {
}
sw.stop();
// System.out.println(sw.getTotalTimeMillis());
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000);
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000);
}
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,8 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
@@ -47,19 +49,36 @@ import static org.junit.Assert.*;
/**
* Unit tests for {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor}
* processing the JSR-303 {@link javax.inject.Inject} annotation.
* processing the JSR-330 {@link javax.inject.Inject} annotation.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testIncompleteBeanDefinition() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
private DefaultListableBeanFactory bf;
private AutowiredAnnotationBeanPostProcessor bpp;
@Before
public void setup() {
bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
}
@After
public void close() {
bf.destroySingletons();
}
@Test
public void testIncompleteBeanDefinition() {
bf.registerBeanDefinition("testBean", new GenericBeanDefinition());
try {
bf.getBean("testBean");
@@ -71,10 +90,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(ResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -92,11 +107,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testExtendedResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -124,11 +134,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testExtendedResourceInjectionWithOverriding() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition annotatedBd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
TestBean tb2 = new TestBean();
annotatedBd.getPropertyValues().add("testBean2", tb2);
@@ -145,16 +150,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
bf.destroySingletons();
}
@Test
public void testExtendedResourceInjectionWithAtRequired() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
@@ -175,11 +174,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testConstructorResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(ConstructorResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -207,10 +201,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testConstructorResourceInjectionWithMultipleCandidatesAsCollection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean",
new RootBeanDefinition(ConstructorsCollectionResourceInjectionBean.class));
TestBean tb = new TestBean();
@@ -226,15 +216,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertEquals(2, bean.getNestedTestBeans().size());
assertSame(ntb1, bean.getNestedTestBeans().get(0));
assertSame(ntb2, bean.getNestedTestBeans().get(1));
bf.destroySingletons();
}
@Test
public void testConstructorResourceInjectionWithMultipleCandidatesAndFallback() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorsResourceInjectionBean.class));
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
@@ -242,15 +227,10 @@ public class InjectAnnotationBeanPostProcessorTests {
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean3());
assertNull(bean.getTestBean4());
bf.destroySingletons();
}
@Test
public void testConstructorInjectionWithMap() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(MapConstructorInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -276,10 +256,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testFieldInjectionWithMap() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(MapFieldInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -305,10 +281,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testMethodInjectionWithMap() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(MapMethodInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -330,10 +302,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testMethodInjectionWithMapAndMultipleMatches() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
@@ -345,15 +313,10 @@ public class InjectAnnotationBeanPostProcessorTests {
catch (BeanCreationException e) {
// expected
}
bf.destroySingletons();
}
@Test
public void testMethodInjectionWithMapAndMultipleMatchesButOnlyOneAutowireCandidate() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
RootBeanDefinition rbd2 = new RootBeanDefinition(TestBean.class);
@@ -366,16 +329,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1"));
assertTrue(bean.getTestBeanMap().values().contains(tb));
assertSame(tb, bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierFieldInjectionBean.class));
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean"));
@@ -384,15 +341,10 @@ public class InjectAnnotationBeanPostProcessorTests {
ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryQualifierInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierFieldInjectionBean.class));
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean"));
@@ -400,16 +352,10 @@ public class InjectAnnotationBeanPostProcessorTests {
ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryFieldInjectionIntoPrototypeBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition annotatedBeanDefinition = new RootBeanDefinition(ObjectFactoryQualifierFieldInjectionBean.class);
annotatedBeanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", annotatedBeanDefinition);
@@ -427,11 +373,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testObjectFactoryMethodInjectionIntoPrototypeBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition annotatedBeanDefinition = new RootBeanDefinition(ObjectFactoryQualifierMethodInjectionBean.class);
annotatedBeanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", annotatedBeanDefinition);
@@ -449,10 +390,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testObjectFactoryWithBeanField() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
@@ -461,15 +398,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryWithBeanMethod() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
@@ -478,15 +410,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryWithTypedListField() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryListFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
@@ -495,15 +422,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryListFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryWithTypedListMethod() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryListMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
@@ -512,15 +434,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryListMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryWithTypedMapField() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryMapFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
@@ -529,15 +446,10 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryMapFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryWithTypedMapMethod() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryMapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
@@ -546,22 +458,15 @@ public class InjectAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryMapMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
/**
* Verifies that a dependency on a {@link org.springframework.beans.factory.FactoryBean} can be autowired via
* {@link org.springframework.beans.factory.annotation.Autowired @Inject}, specifically addressing the JIRA issue
* raised in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-4040"
* target="_blank">SPR-4040</a>.
* Verifies that a dependency on a {@link org.springframework.beans.factory.FactoryBean}
* can be autowired via {@link org.springframework.beans.factory.annotation.Autowired @Inject},
* specifically addressing SPR-4040.
*/
@Test
public void testBeanAutowiredWithFactoryBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("factoryBeanDependentBean", new RootBeanDefinition(FactoryBeanDependentBean.class));
bf.registerSingleton("stringFactoryBean", new StringFactoryBean());
@@ -572,236 +477,152 @@ public class InjectAnnotationBeanPostProcessorTests {
assertNotNull("The factoryBeanDependentBean should have been registered.", bean);
assertEquals("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.",
factoryBean, bean.getFactoryBean());
bf.destroySingletons();
}
@Test
public void testNullableFieldInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testNullableFieldInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableFieldInjectionBean.class));
NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean");
assertNull(bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testNullableMethodInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testNullableMethodInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableMethodInjectionBean.class));
NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean");
assertNull(bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testOptionalFieldInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent());
assertSame(bf.getBean("testBean"), bean.getTestBean().get());
bf.destroySingletons();
}
@Test
public void testOptionalFieldInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalFieldInjectionBean.class));
OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent());
bf.destroySingletons();
}
@Test
public void testOptionalMethodInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent());
assertSame(bf.getBean("testBean"), bean.getTestBean().get());
bf.destroySingletons();
}
@Test
public void testOptionalMethodInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalMethodInjectionBean.class));
OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent());
bf.destroySingletons();
}
@Test
public void testOptionalListFieldInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent());
assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0));
bf.destroySingletons();
}
@Test
public void testOptionalListFieldInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class));
OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent());
bf.destroySingletons();
}
@Test
public void testOptionalListMethodInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent());
assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0));
bf.destroySingletons();
}
@Test
public void testOptionalListMethodInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListMethodInjectionBean.class));
OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent());
bf.destroySingletons();
}
@Test
public void testProviderOfOptionalFieldInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalFieldInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent());
assertSame(bf.getBean("testBean"), bean.getTestBean().get());
bf.destroySingletons();
}
@Test
public void testProviderOfOptionalFieldInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalFieldInjectionBean.class));
ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent());
bf.destroySingletons();
}
@Test
public void testProviderOfOptionalMethodInjectionWithBeanAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalMethodInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent());
assertSame(bf.getBean("testBean"), bean.getTestBean().get());
bf.destroySingletons();
}
@Test
public void testProviderOfOptionalMethodInjectionWithBeanNotAvailable() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalMethodInjectionBean.class));
ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent());
bf.destroySingletons();
}
@Test
public void testAnnotatedDefaultConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor());
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedDefaultConstructorBean.class));
assertNotNull(bf.getBean("annotatedBean"));
@@ -1315,7 +1136,7 @@ public class InjectAnnotationBeanPostProcessorTests {
public static class StringFactoryBean implements FactoryBean<String> {
@Override
public String getObject() throws Exception {
public String getObject() {
return "";
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,6 @@
package org.springframework.beans.factory.config;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import org.junit.After;
@@ -56,7 +53,7 @@ public class PropertyPlaceholderConfigurerTests {
@Before
public void setUp() {
public void setup() {
p1BeanDef = rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${" + P1 + "}")
.getBeanDefinition();
@@ -66,16 +63,14 @@ public class PropertyPlaceholderConfigurerTests {
ppcProperties = new Properties();
ppcProperties.setProperty(P1, P1_LOCAL_PROPS_VAL);
System.setProperty(P1, P1_SYSTEM_PROPS_VAL);
getModifiableSystemEnvironment().put(P1, P1_SYSTEM_ENV_VAL);
ppc = new PropertyPlaceholderConfigurer();
ppc.setProperties(ppcProperties);
}
@After
public void tearDown() {
public void cleanup() {
System.clearProperty(P1);
getModifiableSystemEnvironment().remove(P1);
}
@@ -84,8 +79,8 @@ public class PropertyPlaceholderConfigurerTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
PropertyPlaceholderConfigurer pc = new PropertyPlaceholderConfigurer();
Resource resource = new ClassPathResource("PropertyPlaceholderConfigurerTests.properties", this.getClass());
@@ -95,7 +90,7 @@ public class PropertyPlaceholderConfigurerTests {
@Test
public void resolveFromSystemProperties() {
getModifiableSystemEnvironment().put("otherKey", "systemValue");
System.setProperty("otherKey", "systemValue");
p1BeanDef = rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${" + P1 + "}")
.addPropertyValue("sex", "${otherKey}")
@@ -105,12 +100,12 @@ public class PropertyPlaceholderConfigurerTests {
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL));
assertThat(bean.getSex(), equalTo("systemValue"));
getModifiableSystemEnvironment().remove("otherKey");
System.clearProperty("otherKey");
}
@Test
public void resolveFromLocalProperties() {
tearDown(); // eliminate entries from system props/environment
System.clearProperty(P1);
registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
@@ -134,16 +129,6 @@ public class PropertyPlaceholderConfigurerTests {
assertThat(bean.getName(), equalTo(P1_SYSTEM_PROPS_VAL));
}
@Test
public void setSystemSystemPropertiesMode_toOverride_andResolveFromSystemEnvironment() {
registerWithGeneratedName(p1BeanDef, bf);
System.clearProperty(P1); // will now fall all the way back to system environment
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_SYSTEM_ENV_VAL));
}
@Test
public void setSystemSystemPropertiesMode_toOverride_andSetSearchSystemEnvironment_toFalse() {
registerWithGeneratedName(p1BeanDef, bf);
@@ -160,7 +145,7 @@ public class PropertyPlaceholderConfigurerTests {
* settings regarding resolving properties from the environment.
*/
@Test
public void twoPlacholderConfigurers_withConflictingSettings() {
public void twoPlaceholderConfigurers_withConflictingSettings() {
String P2 = "p2";
String P2_LOCAL_PROPS_VAL = "p2LocalPropsVal";
String P2_SYSTEM_PROPS_VAL = "p2SystemPropsVal";
@@ -178,7 +163,6 @@ public class PropertyPlaceholderConfigurerTests {
ppc.postProcessBeanFactory(bf);
System.setProperty(P2, P2_SYSTEM_PROPS_VAL);
getModifiableSystemEnvironment().put(P2, P2_SYSTEM_ENV_VAL);
Properties ppc2Properties = new Properties();
ppc2Properties.put(P2, P2_LOCAL_PROPS_VAL);
@@ -198,7 +182,6 @@ public class PropertyPlaceholderConfigurerTests {
assertThat(p2Bean.getCountry(), equalTo(P2_SYSTEM_PROPS_VAL));
System.clearProperty(P2);
getModifiableSystemEnvironment().remove(P2);
}
@Test
@@ -210,9 +193,9 @@ public class PropertyPlaceholderConfigurerTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean",
rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "@<key1>")
.addPropertyValue("sex", "${key2}")
.getBeanDefinition());
.addPropertyValue("name", "@<key1>")
.addPropertyValue("sex", "${key2}")
.getBeanDefinition());
System.setProperty("key1", "systemKey1Value");
System.setProperty("key2", "systemKey2Value");
@@ -228,100 +211,41 @@ public class PropertyPlaceholderConfigurerTests {
public void nullValueIsPreserved() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setNullValue("customNull");
getModifiableSystemEnvironment().put("my.name", "customNull");
System.setProperty("my.name", "customNull");
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), nullValue());
getModifiableSystemEnvironment().remove("my.name");
System.clearProperty("my.name");
}
@Test
public void trimValuesIsOffByDefault() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
getModifiableSystemEnvironment().put("my.name", " myValue ");
System.setProperty("my.name", " myValue ");
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue "));
getModifiableSystemEnvironment().remove("my.name");
System.clearProperty("my.name");
}
@Test
public void trimValuesIsApplied() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setTrimValues(true);
getModifiableSystemEnvironment().put("my.name", " myValue ");
System.setProperty("my.name", " myValue ");
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue"));
getModifiableSystemEnvironment().remove("my.name");
System.clearProperty("my.name");
}
@SuppressWarnings("unchecked")
private static Map<String, String> getModifiableSystemEnvironment() {
// for os x / linux
Class<?>[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class<?> cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
try {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
if (obj != null && obj.getClass().getName().equals("java.lang.ProcessEnvironment$StringEnvironment")) {
return (Map<String, String>) obj;
}
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
// for windows
Class<?> processEnvironmentClass;
try {
processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
try {
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Object obj = theCaseInsensitiveEnvironmentField.get(null);
return (Map<String, String>) obj;
}
catch (NoSuchFieldException ex) {
// do nothing
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
try {
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Object obj = theEnvironmentField.get(null);
return (Map<String, String>) obj;
}
catch (NoSuchFieldException ex) {
// do nothing
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
throw new IllegalStateException();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
@@ -41,27 +42,27 @@ public class YamlMapFactoryBeanTests {
@Test
public void testSetIgnoreResourceNotFound() throws Exception {
public void testSetIgnoreResourceNotFound() {
this.factory.setResolutionMethod(YamlMapFactoryBean.ResolutionMethod.OVERRIDE_AND_IGNORE);
this.factory.setResources(new FileSystemResource("non-exsitent-file.yml"));
assertEquals(0, this.factory.getObject().size());
}
@Test(expected = IllegalStateException.class)
public void testSetBarfOnResourceNotFound() throws Exception {
public void testSetBarfOnResourceNotFound() {
this.factory.setResources(new FileSystemResource("non-exsitent-file.yml"));
assertEquals(0, this.factory.getObject().size());
}
@Test
public void testGetObject() throws Exception {
public void testGetObject() {
this.factory.setResources(new ByteArrayResource("foo: bar".getBytes()));
assertEquals(1, this.factory.getObject().size());
}
@SuppressWarnings("unchecked")
@Test
public void testOverrideAndRemoveDefaults() throws Exception {
public void testOverrideAndRemoveDefaults() {
this.factory.setResources(new ByteArrayResource("foo:\n bar: spam".getBytes()),
new ByteArrayResource("foo:\n spam: bar".getBytes()));
@@ -70,7 +71,7 @@ public class YamlMapFactoryBeanTests {
}
@Test
public void testFirstFound() throws Exception {
public void testFirstFound() {
this.factory.setResolutionMethod(YamlProcessor.ResolutionMethod.FIRST_FOUND);
this.factory.setResources(new AbstractResource() {
@Override
@@ -87,7 +88,7 @@ public class YamlMapFactoryBeanTests {
}
@Test
public void testMapWithPeriodsInKey() throws Exception {
public void testMapWithPeriodsInKey() {
this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : value".getBytes()));
Map<String, Object> map = this.factory.getObject();
@@ -102,7 +103,7 @@ public class YamlMapFactoryBeanTests {
}
@Test
public void testMapWithIntegerValue() throws Exception {
public void testMapWithIntegerValue() {
this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : 3".getBytes()));
Map<String, Object> map = this.factory.getObject();
@@ -116,19 +117,10 @@ public class YamlMapFactoryBeanTests {
assertEquals(Integer.valueOf(3), sub.get("key1.key2"));
}
@Test
public void testDuplicateKey() throws Exception {
@Test(expected = DuplicateKeyException.class)
public void testDuplicateKey() {
this.factory.setResources(new ByteArrayResource("mymap:\n foo: bar\nmymap:\n bar: foo".getBytes()));
Map<String, Object> map = this.factory.getObject();
assertEquals(1, map.size());
assertTrue(map.containsKey("mymap"));
Object object = map.get("mymap");
assertTrue(object instanceof LinkedHashMap);
@SuppressWarnings("unchecked")
Map<String, Object> sub = (Map<String, Object>) object;
assertEquals(1, sub.size());
assertEquals("foo", sub.get("bar"));
this.factory.getObject().get("mymap");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.beans.factory.config;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
@@ -29,7 +28,6 @@ import org.yaml.snakeyaml.scanner.ScannerException;
import org.springframework.core.io.ByteArrayResource;
import static org.junit.Assert.*;
import static org.springframework.beans.factory.config.YamlProcessor.*;
/**
* Tests for {@link YamlProcessor}.
@@ -48,91 +46,65 @@ public class YamlProcessorTests {
@Test
public void arrayConvertedToIndexedBeanReference() {
this.processor.setResources(new ByteArrayResource("foo: bar\nbar: [1,2,3]".getBytes()));
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
assertEquals(4, properties.size());
assertEquals("bar", properties.get("foo"));
assertEquals("bar", properties.getProperty("foo"));
assertEquals(1, properties.get("bar[0]"));
assertEquals("1", properties.getProperty("bar[0]"));
assertEquals(2, properties.get("bar[1]"));
assertEquals("2", properties.getProperty("bar[1]"));
assertEquals(3, properties.get("bar[2]"));
assertEquals("3", properties.getProperty("bar[2]"));
}
this.processor.process((properties, map) -> {
assertEquals(4, properties.size());
assertEquals("bar", properties.get("foo"));
assertEquals("bar", properties.getProperty("foo"));
assertEquals(1, properties.get("bar[0]"));
assertEquals("1", properties.getProperty("bar[0]"));
assertEquals(2, properties.get("bar[1]"));
assertEquals("2", properties.getProperty("bar[1]"));
assertEquals(3, properties.get("bar[2]"));
assertEquals("3", properties.getProperty("bar[2]"));
});
}
@Test
public void testStringResource() throws Exception {
public void testStringResource() {
this.processor.setResources(new ByteArrayResource("foo # a document that is a literal".getBytes()));
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
assertEquals("foo", map.get("document"));
}
});
this.processor.process((properties, map) -> assertEquals("foo", map.get("document")));
}
@Test
public void testBadDocumentStart() throws Exception {
public void testBadDocumentStart() {
this.processor.setResources(new ByteArrayResource("foo # a document\nbar: baz".getBytes()));
this.exception.expect(ParserException.class);
this.exception.expectMessage("line 2, column 1");
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
}
});
this.processor.process((properties, map) -> {});
}
@Test
public void testBadResource() throws Exception {
public void testBadResource() {
this.processor.setResources(new ByteArrayResource("foo: bar\ncd\nspam:\n foo: baz".getBytes()));
this.exception.expect(ScannerException.class);
this.exception.expectMessage("line 3, column 1");
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
}
});
this.processor.process((properties, map) -> {});
}
@Test
public void mapConvertedToIndexedBeanReference() {
this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes()));
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
// System.err.println(properties);
assertEquals("bucket", properties.get("bar.spam"));
assertEquals(2, properties.size());
}
this.processor.process((properties, map) -> {
assertEquals("bucket", properties.get("bar.spam"));
assertEquals(2, properties.size());
});
}
@Test
public void integerKeyBehaves() {
this.processor.setResources(new ByteArrayResource("foo: bar\n1: bar".getBytes()));
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
assertEquals("bar", properties.get("[1]"));
assertEquals(2, properties.size());
}
this.processor.process((properties, map) -> {
assertEquals("bar", properties.get("[1]"));
assertEquals(2, properties.size());
});
}
@Test
public void integerDeepKeyBehaves() {
this.processor.setResources(new ByteArrayResource("foo:\n 1: bar".getBytes()));
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
assertEquals("bar", properties.get("foo[1]"));
assertEquals(1, properties.size());
}
this.processor.process((properties, map) -> {
assertEquals("bar", properties.get("foo[1]"));
assertEquals(1, properties.size());
});
}
@@ -140,18 +112,15 @@ public class YamlProcessorTests {
@SuppressWarnings("unchecked")
public void flattenedMapIsSameAsPropertiesButOrdered() {
this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes()));
this.processor.process(new MatchCallback() {
@Override
public void process(Properties properties, Map<String, Object> map) {
assertEquals("bucket", properties.get("bar.spam"));
assertEquals(2, properties.size());
Map<String, Object> flattenedMap = processor.getFlattenedMap(map);
assertEquals("bucket", flattenedMap.get("bar.spam"));
assertEquals(2, flattenedMap.size());
assertTrue(flattenedMap instanceof LinkedHashMap);
Map<String, Object> bar = (Map<String, Object>) map.get("bar");
assertEquals("bucket", bar.get("spam"));
}
this.processor.process((properties, map) -> {
assertEquals("bucket", properties.get("bar.spam"));
assertEquals(2, properties.size());
Map<String, Object> flattenedMap = processor.getFlattenedMap(map);
assertEquals("bucket", flattenedMap.get("bar.spam"));
assertEquals(2, flattenedMap.size());
assertTrue(flattenedMap instanceof LinkedHashMap);
Map<String, Object> bar = (Map<String, Object>) map.get("bar");
assertEquals("bucket", bar.get("spam"));
});
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,11 +19,11 @@ package org.springframework.beans.factory.config;
import java.util.Map;
import java.util.Properties;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;
import org.yaml.snakeyaml.scanner.ScannerException;
import org.springframework.core.io.ByteArrayResource;
@@ -46,17 +46,16 @@ public class YamlPropertiesFactoryBeanTests {
@Test
public void testLoadResource() throws Exception {
public void testLoadResource() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo: bar\nspam:\n foo: baz".getBytes()));
factory.setResources(new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes()));
Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bar"));
assertThat(properties.getProperty("spam.foo"), equalTo("baz"));
}
@Test
public void testBadResource() throws Exception {
public void testBadResource() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo: bar\ncd\nspam:\n foo: baz".getBytes()));
@@ -66,7 +65,7 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadResourcesWithOverride() throws Exception {
public void testLoadResourcesWithOverride() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(
new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes()),
@@ -77,27 +76,24 @@ public class YamlPropertiesFactoryBeanTests {
assertThat(properties.getProperty("foo.bar"), equalTo("spam"));
}
@Test
public void testLoadResourcesWithInternalOverride() throws Exception {
@Test(expected = DuplicateKeyException.class)
public void testLoadResourcesWithInternalOverride() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo: bar\nspam:\n foo: baz\nfoo: bucket".getBytes()));
Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bucket"));
factory.getObject();
}
@Test
@Ignore("We can't fail on duplicate keys because the Map is created by the YAML library")
public void testLoadResourcesWithNestedInternalOverride() throws Exception {
@Test(expected = DuplicateKeyException.class)
public void testLoadResourcesWithNestedInternalOverride() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo:\n bar: spam\n foo: baz\nbreak: it\nfoo: bucket".getBytes()));
Properties properties = factory.getObject();
assertThat(properties.getProperty("foo.bar"), equalTo("spam"));
factory.getObject();
}
@Test
public void testLoadResourceWithMultipleDocuments() throws Exception {
public void testLoadResourceWithMultipleDocuments() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo: bar\nspam: baz\n---\nfoo: bag".getBytes()));
@@ -107,37 +103,29 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadResourceWithSelectedDocuments() throws Exception {
public void testLoadResourceWithSelectedDocuments() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo: bar\nspam: baz\n---\nfoo: bag\nspam: bad".getBytes()));
factory.setDocumentMatchers(new DocumentMatcher() {
@Override
public MatchStatus matches(Properties properties) {
return ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND);
}
});
factory.setDocumentMatchers(properties -> ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND));
Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag"));
assertThat(properties.getProperty("spam"), equalTo("bad"));
}
@Test
public void testLoadResourceWithDefaultMatch() throws Exception {
public void testLoadResourceWithDefaultMatch() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setMatchDefault(true);
factory.setResources(new ByteArrayResource(
"one: two\n---\nfoo: bar\nspam: baz\n---\nfoo: bag\nspam: bad".getBytes()));
factory.setDocumentMatchers(new DocumentMatcher() {
@Override
public MatchStatus matches(Properties properties) {
if (!properties.containsKey("foo")) {
return MatchStatus.ABSTAIN;
}
return ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND);
factory.setDocumentMatchers(properties -> {
if (!properties.containsKey("foo")) {
return MatchStatus.ABSTAIN;
}
return ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND);
});
Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag"));
@@ -146,7 +134,7 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadResourceWithoutDefaultMatch() throws Exception {
public void testLoadResourceWithoutDefaultMatch() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setMatchDefault(false);
factory.setResources(new ByteArrayResource(
@@ -168,20 +156,17 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadResourceWithDefaultMatchSkippingMissedMatch() throws Exception {
public void testLoadResourceWithDefaultMatchSkippingMissedMatch() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setMatchDefault(true);
factory.setResources(new ByteArrayResource(
"one: two\n---\nfoo: bag\nspam: bad\n---\nfoo: bar\nspam: baz".getBytes()));
factory.setDocumentMatchers(new DocumentMatcher() {
@Override
public MatchStatus matches(Properties properties) {
if (!properties.containsKey("foo")) {
return MatchStatus.ABSTAIN;
}
return ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND);
factory.setDocumentMatchers(properties -> {
if (!properties.containsKey("foo")) {
return MatchStatus.ABSTAIN;
}
return ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND);
});
Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag"));
@@ -190,7 +175,7 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadNonExistentResource() throws Exception {
public void testLoadNonExistentResource() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);
factory.setResources(new ClassPathResource("no-such-file.yml"));
@@ -199,7 +184,7 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadNull() throws Exception {
public void testLoadNull() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo: bar\nspam:".getBytes()));
Properties properties = factory.getObject();
@@ -208,7 +193,16 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadArrayOfString() throws Exception {
public void testLoadEmptyArrayValue() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("a: alpha\ntest: []".getBytes()));
Properties properties = factory.getObject();
assertThat(properties.getProperty("a"), equalTo("alpha"));
assertThat(properties.getProperty("test"), equalTo(""));
}
@Test
public void testLoadArrayOfString() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo:\n- bar\n- baz".getBytes()));
Properties properties = factory.getObject();
@@ -218,7 +212,7 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadArrayOfInteger() throws Exception {
public void testLoadArrayOfInteger() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo:\n- 1\n- 2".getBytes()));
Properties properties = factory.getObject();
@@ -228,7 +222,7 @@ public class YamlPropertiesFactoryBeanTests {
}
@Test
public void testLoadArrayOfObject() throws Exception {
public void testLoadArrayOfObject() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo:\n- bar:\n spam: crap\n- baz\n- one: two\n three: four".getBytes()
@@ -246,8 +240,8 @@ public class YamlPropertiesFactoryBeanTests {
public void testYaml() {
Yaml yaml = new Yaml();
Map<String, ?> map = yaml.loadAs("foo: bar\nspam:\n foo: baz", Map.class);
assertThat(map.get("foo"), equalTo((Object) "bar"));
assertThat(((Map<String, Object>) map.get("spam")).get("foo"), equalTo((Object) "baz"));
assertThat(map.get("foo"), equalTo("bar"));
assertThat(((Map<String, Object>) map.get("spam")).get("foo"), equalTo("baz"));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,6 +40,7 @@ import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.core.OverridingClassLoader;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.UrlResource;
@@ -672,6 +673,8 @@ public class BeanFactoryGenericsTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("mock", rbd);
assertEquals(Runnable.class, bf.getType("mock"));
assertEquals(Runnable.class, bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
}
@@ -700,6 +703,10 @@ public class BeanFactoryGenericsTests {
rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
bf.registerBeanDefinition("mock", rbd);
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertEquals(Runnable.class, bf.getType("mock"));
assertEquals(Runnable.class, bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
}
@@ -717,6 +724,10 @@ public class BeanFactoryGenericsTests {
rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class.getName());
bf.registerBeanDefinition("mock", rbd);
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertEquals(Runnable.class, bf.getType("mock"));
assertEquals(Runnable.class, bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
}
@@ -732,6 +743,10 @@ public class BeanFactoryGenericsTests {
rbd.getConstructorArgumentValues().addGenericArgumentValue(new TypedStringValue(Runnable.class.getName()));
bf.registerBeanDefinition("mock", rbd);
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertEquals(Runnable.class, bf.getType("mock"));
assertEquals(Runnable.class, bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
}
@@ -749,6 +764,10 @@ public class BeanFactoryGenericsTests {
rbd.getConstructorArgumentValues().addGenericArgumentValue("x");
bf.registerBeanDefinition("mock", rbd);
assertFalse(bf.isTypeMatch("mock", Runnable.class));
assertFalse(bf.isTypeMatch("mock", Runnable.class));
assertNull(bf.getType("mock"));
assertNull(bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(0, beans.size());
}
@@ -766,6 +785,32 @@ public class BeanFactoryGenericsTests {
rbd.getConstructorArgumentValues().addIndexedArgumentValue(0, Runnable.class);
bf.registerBeanDefinition("mock", rbd);
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertEquals(Runnable.class, bf.getType("mock"));
assertEquals(Runnable.class, bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
}
@Test // SPR-16720
public void parameterizedInstanceFactoryMethodWithTempClassLoader() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setTempClassLoader(new OverridingClassLoader(getClass().getClassLoader()));
RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
bf.registerBeanDefinition("mocksControl", rbd);
rbd = new RootBeanDefinition();
rbd.setFactoryBeanName("mocksControl");
rbd.setFactoryMethodName("createMock");
rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
bf.registerBeanDefinition("mock", rbd);
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertTrue(bf.isTypeMatch("mock", Runnable.class));
assertEquals(Runnable.class, bf.getType("mock"));
assertEquals(Runnable.class, bf.getType("mock"));
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
}
@@ -0,0 +1,29 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests.sample.beans;
public interface AgeHolder {
default int age() {
return getAge();
}
int getAge();
void setAge(int age);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,11 +27,7 @@ import java.io.IOException;
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface ITestBean {
int getAge();
void setAge(int age);
public interface ITestBean extends AgeHolder {
String getName();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,8 +46,7 @@ import javax.lang.model.element.TypeElement;
public class CandidateComponentsIndexer implements Processor {
private static final Set<ElementKind> TYPE_KINDS =
Collections.unmodifiableSet(EnumSet.of(ElementKind.CLASS,
ElementKind.INTERFACE));
Collections.unmodifiableSet(EnumSet.of(ElementKind.CLASS, ElementKind.INTERFACE));
private MetadataStore metadataStore;
@@ -135,10 +134,10 @@ public class CandidateComponentsIndexer implements Processor {
private static List<TypeElement> staticTypesIn(Iterable<? extends Element> elements) {
List<TypeElement> list = new ArrayList<>();
for (Element e : elements) {
if (TYPE_KINDS.contains(e.getKind())
&& e.getModifiers().contains(Modifier.STATIC))
list.add(TypeElement.class.cast(e));
for (Element element : elements) {
if (TYPE_KINDS.contains(element.getKind()) && element.getModifiers().contains(Modifier.STATIC)) {
list.add(TypeElement.class.cast(element));
}
}
return list;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,9 +62,9 @@ class TypeHelper {
DeclaredType declaredType = (DeclaredType) type;
Element enclosingElement = declaredType.asElement().getEnclosingElement();
if (enclosingElement != null && enclosingElement instanceof TypeElement) {
return getQualifiedName(enclosingElement) + "$"
+ declaredType.asElement().getSimpleName().toString();
} else {
return getQualifiedName(enclosingElement) + "$" + declaredType.asElement().getSimpleName().toString();
}
else {
return getQualifiedName(declaredType.asElement());
}
}
@@ -85,7 +85,7 @@ class TypeHelper {
public Element getSuperClass(Element element) {
List<? extends TypeMirror> superTypes = this.types.directSupertypes(element.asType());
if (superTypes.isEmpty()) {
return null; // reached java.lang.Object
return null; // reached java.lang.Object
}
return this.types.asElement(superTypes.get(0));
}
@@ -16,7 +16,7 @@ dependencies {
optional("org.freemarker:freemarker:${freemarkerVersion}")
testCompile(project(":spring-context"))
testCompile("org.hsqldb:hsqldb:${hsqldbVersion}")
testCompile("org.hibernate:hibernate-validator:6.0.9.Final")
testCompile("org.hibernate:hibernate-validator:6.0.10.Final")
testCompile("javax.annotation:javax.annotation-api:1.3.2")
testRuntime("org.ehcache:jcache:1.0.1")
testRuntime("org.ehcache:ehcache:3.4.0")
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,7 @@ import org.springframework.cache.jcache.interceptor.JCacheOperationSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.lang.Nullable;
/**
* Abstract JSR-107 specific {@code @Configuration} class providing common
@@ -37,8 +38,10 @@ import org.springframework.context.annotation.Role;
@Configuration
public class AbstractJCacheConfiguration extends AbstractCachingConfiguration {
@Nullable
protected CacheResolver exceptionCacheResolver;
@Override
protected void useCachingConfigurer(CachingConfigurer config) {
super.useCachingConfigurer(config);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cache.jcache.config;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.lang.Nullable;
/**
* Extension of {@link CachingConfigurer} for the JSR-107 implementation.
@@ -58,6 +59,7 @@ public interface JCacheConfigurer extends CachingConfigurer {
* </pre>
* See {@link org.springframework.cache.annotation.EnableCaching} for more complete examples.
*/
@Nullable
CacheResolver exceptionCacheResolver();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cache.jcache.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.lang.Nullable;
/**
* An extension of {@link CachingConfigurerSupport} that also implements
@@ -34,6 +35,7 @@ import org.springframework.cache.interceptor.CacheResolver;
public class JCacheConfigurerSupport extends CachingConfigurerSupport implements JCacheConfigurer {
@Override
@Nullable
public CacheResolver exceptionCacheResolver() {
return null;
}

Some files were not shown because too many files have changed in this diff Show More