Commit Graph

506 Commits

Author SHA1 Message Date
Chris Beams d9f7fdd120 Support reading nested annotations via ASM
Background

  Spring 3.1 introduced the @ComponentScan annotation, which can accept
  an optional array of include and/or exclude @Filter annotations, e.g.

     @ComponentScan(
         basePackages = "com.acme.app",
         includeFilters = { @Filter(MyStereotype.class), ... }
     )
     @Configuration
     public class AppConfig { ... }

  @ComponentScan and other annotations related to @Configuration class
  processing such as @Import, @ImportResource and the @Enable*
  annotations are parsed using reflection in certain code paths, e.g.
  when registered directly against AnnotationConfigApplicationContext,
  and via ASM in other code paths, e.g. when a @Configuration class is
  discovered via an XML bean definition or when included via the
  @Import annotation.

  The ASM-based approach is designed to avoid premature classloading of
  user types and is instrumental in providing tooling support (STS, etc).

  Prior to this commit, the ASM-based routines for reading annotation
  attributes were unable to recurse into nested annotations, such as in
  the @Filter example above. Prior to Spring 3.1 this was not a problem,
  because prior to @ComponentScan, there were no cases of nested
  annotations in the framework.

  This limitation manifested itself in cases where users encounter
  the ASM-based annotation parsing code paths AND declare
  @ComponentScan annotations with explicit nested @Filter annotations.
  In these cases, the 'includeFilters' and 'excludeFilters' attributes
  are simply empty where they should be populated, causing the framework
  to ignore the filter directives and provide incorrect results from
  component scanning.

  The purpose of this change then, is to introduce the capability on the
  ASM side to recurse into nested annotations and annotation arrays. The
  challenge in doing so is that the nested annotations themselves cannot
  be realized as annotation instances, so must be represented as a
  nested Map (or, as described below, the new AnnotationAttributes type).

  Furthermore, the reflection-based annotation parsing must also be
  updated to treat nested annotations in a similar fashion; even though
  the reflection-based approach has no problem accessing nested
  annotations (it just works out of the box), for substitutability
  against the AnnotationMetadata SPI, both ASM- and reflection-based
  implementations should return the same results in any case. Therefore,
  the reflection-based StandardAnnotationMetadata has also been updated
  with an optional 'nestedAnnotationsAsMap' constructor argument that is
  false by default to preserve compatibility in the rare case that
  StandardAnnotationMetadata is being used outside the core framework.
  Within the framework, all uses of StandardAnnotationMetadata have been
  updated to set this new flag to true, meaning that nested annotation
  results will be consistent regardless the parsing approach used.

  Spr9031Tests corners this bug and demonstrates that nested @Filter
  annotations can be parsed and read in both the ASM- and
  reflection-based paths.

Major changes

 - AnnotationAttributes has been introduced as a concrete
   LinkedHashMap<String, Object> to be used anywhere annotation
   attributes are accessed, providing error reporting on attribute
   lookup and convenient type-safe access to common annotation types
   such as String, String[], boolean, int, and nested annotation and
   annotation arrays, with the latter two also returned as
   AnnotationAttributes instances.

 - AnnotationUtils#getAnnotationAttributes methods now return
   AnnotationAttributes instances, even though for binary compatibility
   the signatures of these methods have been preserved as returning
   Map<String, Object>.

 - AnnotationAttributes#forMap provides a convenient mechanism for
   adapting any Map<String, Object> into an AnnotationAttributes
   instance. In the case that the Map is already actually of
   type AnnotationAttributes, it is simply casted and returned.
   Otherwise, the map is supplied to the AnnotationAttributes(Map)
   constructor and wrapped in common collections style.

 - The protected MetadataUtils#attributesFor(Metadata, Class) provides
   further convenience in the many locations throughout the
   .context.annotation packagage that depend on annotation attribute
   introspection.

 - ASM-based core.type.classreading package reworked

   Specifically, AnnotationAttributesReadingVisitor has been enhanced to
   support recursive reading of annotations and annotation arrays, for
   example in @ComponentScan's nested array of @Filter annotations,
   ensuring that nested AnnotationAttributes objects are populated as
   described above.

   AnnotationAttributesReadingVisitor has also been refactored for
   clarity, being broken up into several additional ASM
   AnnotationVisitor implementations. Given that all types are
   package-private here, these changes represent no risk to binary
   compatibility.

 - Reflection-based StandardAnnotationMetadata updated

   As described above, the 'nestedAnnotationsAsMap' constructor argument
   has been added, and all framework-internal uses of this class have
   been updated to set this flag to true.

Issue: SPR-7979, SPR-8719, SPR-9031
2012-02-07 21:57:49 +01:00
Chris Beams 17cf465d23 Fix method equality bug in ExtendedBeanInfo
A number of users reported issues with comparing method identity vs
equivalence when discovering JavaBeans property methods in
ExtendedBeanInfo.

This commit updates the implementation to consistently use '.equals()'
instead of '=='.

Issue: SPR-8079, SPR-8347
2012-02-02 15:24:52 +01:00
Chris Beams 87a021d5c9 Add <license> section to 3.1.x Maven poms
Issue: SPR-8927
2012-01-31 15:18:05 +01:00
Juergen Hoeller d331c5d1c9 correctly handle ParseException from Formatter for String->String case (SPR-8944) 2011-12-22 16:30:22 +01:00
Juergen Hoeller 86bef9030f correctly handle ParseException from Formatter for String->String case (SPR-8944) 2011-12-22 15:54:17 +01:00
Chris Beams 41c405998e Convert CRLF=>LF on files missed earlier
Complete pass with `dos2unix` found additional files missed on earlier
related commit.

Issue: SPR-5608
2011-12-22 14:06:44 +01:00
Chris Beams 88913f2b23 Convert CRLF (dos) to LF (unix)
Prior to this change, roughly 5% (~300 out of 6000+) of files under the
source tree had CRLF line endings as opposed to the majority which have
LF endings.

This change normalizes these files to LF for consistency going forward.

Command used:

$ git ls-files | xargs file | grep CRLF | cut -d":" -f1 | xargs dos2unix

Issue: SPR-5608
2011-12-21 14:52:47 +01:00
Chris Beams e158f61e93 Increment version to 3.1.1.BUILD-SNAPSHOT 2011-12-16 11:59:06 +01:00
Chris Beams ac107d0c2a Release Spring Framework 3.1.0.RELEASE 2011-12-13 16:35:49 +00:00
Chris Beams 48836e2ebb Allow parameters in FactoryBean-returning @Bean methods
Prior to this change, an assumption was made in
AbstractAutowireCapableBeanFactory that any factory-method would have
zero parameters.  This may not be the case in @Bean methods.

We now look for the factory-method by name in a more flexible fashion
that accomodates the possibility of method parameters.

There remains at least one edge cases here where things could still fail,
for example a @Configuration class could have two FactoryBean-returning
methods of the same name, but each with different generic FactoryBean
types and different parameter lists. In this case, the implementation
may infer and return the wrong object type, as it currently returns
the first match for the given factory-method name.  The complexity cost
of ensuring that this never happens is not likely worth the trouble
given the very low likelihood of such an arrangement.

Issue: SPR-8762
2011-12-10 19:32:02 +00:00
Juergen Hoeller 569426dfdf restored DataBinder's ability to bind to an auto-growing List with unknown element type (SPR-8828) 2011-12-07 21:27:26 +00:00
Juergen Hoeller 84be348cb0 log or rethrow original ConversionFailedException as appropriate 2011-12-03 15:57:19 +00:00
Juergen Hoeller 1a2bbe5c4d consistent specification of standard meta-annotations 2011-12-03 15:47:10 +00:00
Juergen Hoeller dc41daa3db renamed 'isJava6VisibilityBridgeMethodPair' to 'isVisibilityBridgeMethodPair' (SPR-8660) 2011-12-01 13:14:06 +00:00
Juergen Hoeller 450c75337f fixed getAsText javadoc (SPR-7890) 2011-11-28 21:14:40 +00:00
Juergen Hoeller aa7fcb5431 polishing 2011-11-28 18:38:26 +00:00
Chris Beams 549c663fba Fix generics warnings in AbstractBeanFactory 2011-11-24 21:40:02 +00:00
Chris Beams 0113ea91a3 Support by-type lookup/injection of primitive types
Allowing beans of primitive type to be looked up via getBean(Class), or
to be injected using @Autowired or @Injected or @Resource. Prior to
these changes, an attempt to lookup or inject a bean of, for example,
type boolean would fail because all spring beans are Objects, regardless
of initial type due to the way that ObjectFactory works.

Now these attempts to lookup or inject primitive types work, thanks to
simple changes in AbstractBeanFactory using ClassUtils#isAssignable
methods instead of the built-in Class#isAssignableFrom. The former takes
into account primitives and their object wrapper types, whereas the
latter does not.

The need to declare, look up or inject primitive-typed beans is probably
low -- how often does one need a bean of type boolean or int after all?.
Prior to the introduction of @Bean methods in Spring 3.0, it was not
possible in practice to register primitive beans, so this issue never
came up. Now that one can declare primitive-typed beans, it does make
sense that we properly support by-type lookup and injection without
forcing the user to work with object wrappers.

Issue: SPR-8874
2011-11-24 21:39:58 +00:00
Chris Beams b2ae3dbb47 Avoid 'type mismatch' errors in ExtendedBeanInfo
Certain edge cases around return type covariance can trigger an
IntrospectionException when trying to create a new PropertyDescriptor;
particularly around the addition of write methods with parameter types
that do not match read method return types.

These type mismatch exceptions are raised during normal Introspector
operations as well (i.e. without ExtendedBeanInfo in the mix), but
the Introspector intentionally supresses them. In covariance cases,
there is often already a suitable write method present, e.g. discovered
in a supertype or superinterface, that, with the benefit of bridge
methods works just fine in practice at runtime.  That is to say, in
these suppression cases, the rejection of the write method is 'OK' in
that there is already a write method present that can handle a call.

ExtendedBeanInfo now mirrors this suppression behavior, but does issue
a WARN-level log message to let the user know.

An important effect of this change is that ExtendedBeanInfo now modifies
the delegate BeanInfo object, whereas previously it did not. In practice
this probably matters very little, but it is a design change worth
noting. The reason for this change was to avoid the need to create new
PropertyDescriptors wherever possible. It was discovered that by updating
existing PDs, one can avoid these IntrospectionExceptions a greater
percentage of the time.

Issue: SPR-8806
2011-11-19 21:07:10 +00:00
Sam Brannen c0b3b7b81e Added cross linking in Javadoc for @Autowired, @Qualifier, and @Value. 2011-11-11 22:28:37 +00:00
Juergen Hoeller 79bcefa0ce optimized DefaultListableBeanFactory's PropertyDescriptor caching for concurrent access (SPR-7863) 2011-10-20 12:04:01 +00:00
Chris Beams 38e90105a0 Support destroy method inference
Anywhere the value of a destroy method may be expressed, specifying
the value "(inferred)" now indicates that the container should attempt
to automatically discover a destroy method. This functionality is
currently limited to detecting public, no-arg methods named 'close';
this is particularly useful for commonly used types such as Hibernate
SessionFactory most JDBC DataSource implementations, JMS connection
factories, and so forth.

This special value is captured as the constant
AbstractBeanDefinition#INFER_METHOD, which in turn serves as the default
value of the @Bean#destroyMethod attribute.

For example in the following case

    @Bean
    public BasicDataSource dataSource() { ... }

the container will automatically detect BasicDataSource#close and invoke
it when the enclosing ApplicationContext is closed. This is exactly
equivalent to

    @Bean(destroyMethod="(inferred)")
    public BasicDataSource dataSource() { ... }

A user may override this inference-by-default convention simply by
specifying a different method

    @Bean(destroyMethod="myClose")
    public MyBasicDataSource dataSource() { ... }

or, in the case of a bean that has an otherwise inferrable 'close'
method, but the user wishes to disable handling it entirely, an empty
string may be specified

    @Bean(destroyMethod="")
    public MyBasicDataSource dataSource() { ... }

The special destroy method name "(inferred)" may also be specified in
an XML context, e.g.

    <bean destroy-method="(inferred)">
        or
    <beans default-destroy-method="(inferred)">

Note that "(inferred)" is the default value for @Bean#destroyMethod,
but NOT for the destroy-method and default-destroy-method attributes
in the spring-beans XML schema.

The principal reason for introducing this feature is to avoid forcing
@Configuration class users to type destroyMethod="close" every time a
closeable bean is configured. This kind of boilerplate is easily
forgotten, and this simple convention means the right thing is done
by default, while allowing the user full control over customization or
disablement in special cases.

Issue: SPR-8751
2011-10-12 02:09:04 +00:00
Chris Beams 8cafb7ee13 Fix warnings in DisposableBeanAdapter 2011-10-12 02:08:52 +00:00
Chris Beams 980c15d578 Distinguish between different bridge method types
Add BridgeMethodResolver#isJava6VisibilityBridgeMethodPair to
distinguish between (a) bridge methods introduced in Java 6 to
compensate for inheriting public methods from non-public superclasses
and (b) bridge methods that have existed since Java 5 to accommodate
return type covariance and generic parameters.

In the former case, annotations should be looked up from the original
bridged method (SPR-7900).  In the latter, the annotation should be
looked up against the bridge method itself (SPR-8660).

As noted in the Javadoc for the new method, see
http://stas-blogspot.blogspot.com/2010/03/java-bridge-methods-explained.html
for a useful description of the various types of bridge methods, as
well as http://bugs.sun.com/view_bug.do?bug_id=6342411, the bug fixed in
Java 6 resulting in the introduction of 'visibility bridge methods'.

Issue: SPR-8660, SPR-7900
2011-10-10 05:40:21 +00:00
Chris Beams 9ba1d1437d Give ExtendedBeanInfo package-private visibility
Issue: SPR-8079
2011-10-09 07:54:44 +00:00
Chris Beams 34956d30b3 Fix doc typo in AbstractAutowireCapableBeanFactory 2011-09-27 18:16:20 +00:00
Chris Beams 10be0ef9e7 Clarify BeanFactory#containsBean Javadoc
Previously, #containsBean Javadoc advertised that a true return value
indicates that a call to #getBean for the same name would succeed.

This is actually not the case, and has never been.  The semantics
of #containsBean have always been to indicate whether a bean definition
with the given name is definied or a singleton instance with the given
name has been registered.

The Javadoc now reflects this accurately.

Issue: SPR-8690
2011-09-13 22:09:12 +00:00
Chris Beams a456a1a0e3 Improve annotation processing thread-safety
Commit http://bit.ly/nXumTs ensured that component methods and fields
marked with 'common annotations' such as @Resource, @PostConstruct and
@PreDestroy are invoked/assigned once and only once, even if multiple
instances of the CommonAnnotationBeanPostProcessor are processing the
same bean factory.

The implementation works against the InjectionMetadata API, adding and
removing these members from sets that track whether they are already
'externally managed', i.e. that another CABPP has already handled them,
thus avoiding redundant processing.

Prior to this change, the #remove operations against these sets were
not synchronized. In a single-threaded context this is fine thanks to
logic in AbstractAutowireCapableBeanFactory#doCreateBean that checks to
see whether a given bean definition has already been post processed.
However, as reported by SPR-8598, certain cases involving multiple
threads and annotated prototype-scoped beans can cause concurrent
modification exceptions during the #remove operation (ostensibly because
another thread is attempting to do the same removal at the same time,
though this has yet to be reproduced in isolation).

Now the sets originally introduced by the commit above are decorated
with Collections#synchronizedSet and any iterations over those sets
are synchronized properly. This change should have low performance
impact as such processing happens at container startup time (save for
non-singleton lookups at runtime), and there should be little
contention in any case.

Issue: SPR-8598
2011-09-12 23:05:01 +00:00
Sam Brannen 1de71c6e37 [SPR-8222] Upgraded to JUnit 4.9. 2011-08-30 13:16:12 +00:00
Chris Beams 71984b8038 Fix ExtendedBeanInfo indexed write method edge case
See comments at ExtendedBeanInfo#reproSpr8522

Issue: SPR-8522
2011-08-29 05:31:47 +00:00
Sam Brannen 0a88d4bae1 Fixed broken test: now verifying that an attempt to set a null active profile throws an IllegalArgumentException. 2011-08-20 14:58:58 +00:00
Sam Brannen 87dad65ff0 [SPR-8622] Upgraded to JUnit 4.8.2 2011-08-18 16:06:31 +00:00
Juergen Hoeller f6be50eda2 RequiredAnnotationBeanPostProcessor's skip attribute accepts "true" as String value as well (SPR-8617) 2011-08-16 22:41:11 +00:00
Juergen Hoeller 8f23c66512 SpringBeanAutowiringSupport is able to process @Value annotations on any given target instance (SPR-8574) 2011-08-03 10:19:27 +00:00
Juergen Hoeller 1baf2a3981 polishing 2011-07-28 11:15:11 +00:00
Chris Beams 226256e264 Respect <description> within <entry> per beans XSD
Prior to this change, a parsing exception would be thrown if a
<description> element was placed within a <map><entry/></map>
element. The beans XSD has always permitted this arrangement,
but BeanDefinitionParserDelegate did not respect it. The latter now
simply ignores any <description> element, rather than failing.

Issue: SPR-8563
2011-07-28 02:21:22 +00:00
Juergen Hoeller f432f3043f DefaultListableBeanFactory allows for init methods to register further bean definitions (again; SPR-7757) 2011-07-27 22:51:26 +00:00
Juergen Hoeller d97a5bf889 minor javadoc revision 2011-07-18 21:50:15 +00:00
Chris Beams 807d612978 Determine FactoryBean object type via generics
For the particular use case detailed in SPR-8514, with this change we
now attempt to determine the object type of a FactoryBean through its
generic type parameter if possible.

For (a contrived) example:

@Configuration
public MyConfig {
    @Bean
    public FactoryBean<String> fb() {
        return new StringFactoryBean("foo");
    }
}

The implementation will now look at the <String> generic parameter
instead of attempting to instantiate the FactoryBean in order to call
its #getObjectType() method.

This is important in order to avoid the autowiring lifecycle issues
detailed in SPR-8514.  For example, prior to this change, the following
code would fail:

@Configuration
public MyConfig {
    @Autowired Foo foo;

    @Bean
    public FactoryBean<String> fb() {
        Assert.notNull(foo);
        return new StringFactoryBean("foo");
    }
}

The reason for this failure is that in order to perform autowiring,
the container must first determine the object type of all configured
FactoryBeans.  Clearly a chicken-and-egg issue, now fixed by this
change.

And lest this be thought of as an obscure bug, keep in mind the use case
of our own JPA support: in order to configure and return a
LocalContainerEntityManagerFactoryBean from a @Bean method, one will
need access to a DataSource, etc -- resources that are likely to
be @Autowired across @Configuration classes for modularity purposes.

Note that while the examples above feature methods with return
types dealing directly with the FactoryBean interface, of course
the implementation deals with subclasses/subinterfaces of FactoryBean
equally as well.  See ConfigurationWithFactoryBeanAndAutowiringTests
for complete examples.

There is at least a slight risk here, in that the signature of a
FactoryBean-returing @Bean method may advertise a generic type for the
FactoryBean less specific than the actual object returned (or than
advertised by #getObjectType for that matter). This could mean that an
autowiring target may be missed, that we end up with a kind of
autowiring 'false negative' where FactoryBeans are concerned. This is
probably a less common scenario than the need to work with an autowired
field within a FactoryBean-returning @Bean method, and also has a clear
workaround of making the generic return type more specific.

Issue: SPR-8514
2011-07-06 09:15:37 +00:00
Juergen Hoeller 38290485de switched from readResolve to readObject 2011-07-04 21:21:33 +00:00
Juergen Hoeller 57998293c8 optimized debug logging in case of non-convertible collection (SPR-8499) 2011-07-04 09:43:08 +00:00
Juergen Hoeller 22939b6d05 properly wrap IndexOutOfBoundsException even for List 2011-07-03 20:24:12 +00:00
Juergen Hoeller b8f7d324af regular IndexOutOfBoundsException if index beyond auto-grow limit 2011-07-03 20:12:18 +00:00
Juergen Hoeller b9fe1b3250 restored original array behavior (no default growth of arrays) 2011-07-03 20:05:07 +00:00
Juergen Hoeller 4c75054f90 DataBinder uses a default limit of 256 for array/collection auto-growing (SPR-7842) 2011-07-03 19:26:49 +00:00
Chris Beams 4262aed9c8 Refactor BeanFactoryLocator to use getBean(Class)
Prior to this change, (Context)SingletonBeanFactoryLocator used
BeanFactoryUtils#beanOfType(ListableBeanFactory, Class) to locate the
bean of type BeanFactory.

The more modern approach is to use BeanFactory#getBean(Class), which
removes a dependency on ListableBeanFactory interface while at the same
time opening the implementation up to respecting autowiring exclusions,
primary metadata, etc.

Issue: SPR-8489
2011-07-02 22:22:33 +00:00
Juergen Hoeller c0dfbdeebc DefaultListableBeanFactory is only deserializable through a SerializedBeanFactoryReference 2011-06-22 20:56:23 +00:00
Juergen Hoeller e0d558b084 getBean(name, type) attempts type conversion if necessary (SPR-8480) 2011-06-22 20:52:28 +00:00
Chris Beams 41e5d55d52 Fix bridge method detection for class hierarchies
Prior to this change, @Autowired injection against an instance of a
subclass having different visibility than its superclass would fail
if the @Autowired method is declared only in the superclass. This is due
to an apparent change in the rules around bridge method generation
between Java 5 and Java 6, and possibly even varying across compiler
vendors.

Now, BridgeMethodResolver is used consistently when detecting
@Autowired, @Inject and @Resource metadata to bypass these bridge
methods if they exist.

Issue: SPR-7900
2011-06-21 14:59:37 +00:00
Chris Beams 4fc386a4f5 Provide default ParameterNameDiscoverer for AACBF
Prior to this change, AbstractAutowireCapableBeanFactory did not support
a default ParameterNameDiscoverer.  This meant that attempting to use
<constructor-arg name=".."> syntax would fail (with a fairly obscure
exception) as that feature depends on a ParameterNameDiscoverer to
introspect the constructor arguments.

This lack of a default was originally intended to avoid a dependency on
ASM, but now that (a) .asm is a built-in module and (b) .beans has a
non-optional compile-time dependency on .asm, there is no reason not to
provide this default.

The net effect is that in a number of locations throughout the
framework, namely in GenericApplicationContext and
AbstractRefreshableApplicationContext, it is no longer necessary to
explicitly call AACBF#setParameterNameDiscoverer. This also means that
using a naked BeanFactory (likely for testing scenarios) is that much
easier.

Issue: SPR-8184
2011-06-17 09:47:19 +00:00