language stringclasses 1
value | owner stringlengths 2 15 | repo stringlengths 2 21 | sha stringlengths 45 45 | message stringlengths 7 36.3k | path stringlengths 1 199 | patch stringlengths 15 102k | is_multipart bool 2
classes |
|---|---|---|---|---|---|---|---|
Other | spring-projects | spring-framework | 2afeb08e3c387715374c81a82074bae4235b5082.json | Fix @Autowired+@PostConstruct+@Configuration issue
A subtle issue existed with the way we relied on isCurrentlyInCreation
to determine whether a @Bean method is being called by the container
or by user code. This worked in most cases, but in the particular
scenario laid out by SPR-8080, this approach was no longer sufficient.
This change introduces a ThreadLocal that contains the factory method
currently being invoked by the container, such that enhanced @Bean
methods can check against it to see if they are being called by the
container or not. If so, that is the cue that the user-defined @Bean
method implementation should be invoked in order to actually create
the bean for the first time. If not, then the cached instance of
the already-created bean should be looked up and returned.
See ConfigurationClassPostConstructAndAutowiringTests for
reproduction cases and more detail.
Issue: SPR-8080 | org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java | @@ -97,6 +97,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
/** Names of beans that are currently in creation */
private final Set<String> singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet<String>());
+ /** Names of beans currently excluded from in creation checks */
+ private final Set<String> inCreationCheckExclusions = new HashSet<String>();
+
/** List of suppressed Exceptions, available for associating related causes */
private Set<Exception> suppressedExceptions;
@@ -293,7 +296,7 @@ public int getSingletonCount() {
* @see #isSingletonCurrentlyInCreation
*/
protected void beforeSingletonCreation(String beanName) {
- if (!this.singletonsCurrentlyInCreation.add(beanName)) {
+ if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
@@ -305,11 +308,19 @@ protected void beforeSingletonCreation(String beanName) {
* @see #isSingletonCurrentlyInCreation
*/
protected void afterSingletonCreation(String beanName) {
- if (!this.singletonsCurrentlyInCreation.remove(beanName)) {
+ if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
+ public final void setCurrentlyInCreation(String beanName, boolean inCreation) {
+ if (!inCreation) {
+ this.inCreationCheckExclusions.add(beanName);
+ } else {
+ this.inCreationCheckExclusions.remove(beanName);
+ }
+ }
+
/**
* Return whether the specified singleton bean is currently in creation
* (within the entire factory). | true |
Other | spring-projects | spring-framework | 2afeb08e3c387715374c81a82074bae4235b5082.json | Fix @Autowired+@PostConstruct+@Configuration issue
A subtle issue existed with the way we relied on isCurrentlyInCreation
to determine whether a @Bean method is being called by the container
or by user code. This worked in most cases, but in the particular
scenario laid out by SPR-8080, this approach was no longer sufficient.
This change introduces a ThreadLocal that contains the factory method
currently being invoked by the container, such that enhanced @Bean
methods can check against it to see if they are being called by the
container or not. If so, that is the cue that the user-defined @Bean
method implementation should be invoked in order to actually create
the bean for the first time. If not, then the cached instance of
the already-created bean should be looked up and returned.
See ConfigurationClassPostConstructAndAutowiringTests for
reproduction cases and more detail.
Issue: SPR-8080 | org.springframework.beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java | @@ -42,6 +42,8 @@
*/
public class SimpleInstantiationStrategy implements InstantiationStrategy {
+ private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<Method>();
+
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (beanDefinition.getMethodOverrides().isEmpty()) {
@@ -140,9 +142,19 @@ public Object run() {
else {
ReflectionUtils.makeAccessible(factoryMethod);
}
-
- // It's a static method if the target is null.
- return factoryMethod.invoke(factoryBean, args);
+
+ Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
+ try {
+ currentlyInvokedFactoryMethod.set(factoryMethod);
+ return factoryMethod.invoke(factoryBean, args);
+ } finally {
+ if (priorInvokedFactoryMethod != null) {
+ currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
+ }
+ else {
+ currentlyInvokedFactoryMethod.remove();
+ }
+ }
}
catch (IllegalArgumentException ex) {
throw new BeanDefinitionStoreException(
@@ -159,4 +171,12 @@ public Object run() {
}
}
+ /**
+ * Return the factory method currently being invoked or {@code null} if none.
+ * Allows factory method implementations to determine whether the current
+ * caller is the container itself as opposed to user code.
+ */
+ public static Method getCurrentlyInvokedFactoryMethod() {
+ return currentlyInvokedFactoryMethod.get();
+ }
} | true |
Other | spring-projects | spring-framework | 2afeb08e3c387715374c81a82074bae4235b5082.json | Fix @Autowired+@PostConstruct+@Configuration issue
A subtle issue existed with the way we relied on isCurrentlyInCreation
to determine whether a @Bean method is being called by the container
or by user code. This worked in most cases, but in the particular
scenario laid out by SPR-8080, this approach was no longer sufficient.
This change introduces a ThreadLocal that contains the factory method
currently being invoked by the container, such that enhanced @Bean
methods can check against it to see if they are being called by the
container or not. If so, that is the cue that the user-defined @Bean
method implementation should be invoked in order to actually create
the bean for the first time. If not, then the cached instance of
the already-created bean should be looked up and returned.
See ConfigurationClassPostConstructAndAutowiringTests for
reproduction cases and more detail.
Issue: SPR-8080 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java | @@ -35,6 +35,7 @@
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
+import org.springframework.beans.factory.support.SimpleInstantiationStrategy;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
@@ -233,23 +234,42 @@ public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object
return enhanceFactoryBean(factoryBean.getClass(), beanName);
}
}
-
- // the bean is not a FactoryBean - check to see if it has been cached
- if (factoryContainsBean(beanName)) {
- // we have an already existing cached instance of this bean -> retrieve it
- return this.beanFactory.getBean(beanName);
- }
- if (BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
- logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " +
- "assignable to Spring's BeanFactoryPostProcessor interface. This will " +
- "result in a failure to process annotations such as @Autowired, " +
- "@Resource and @PostConstruct within the method's declaring " +
- "@Configuration class. Add the 'static' modifier to this method to avoid" +
- "these container lifecycle issues; see @Bean Javadoc for complete details",
- beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
+ boolean factoryIsCaller = beanMethod.equals(SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod());
+ boolean factoryAlreadyContainsSingleton = this.beanFactory.containsSingleton(beanName);
+ if (factoryIsCaller && !factoryAlreadyContainsSingleton) {
+ // the factory is calling the bean method in order to instantiate and register the bean
+ // (i.e. via a getBean() call) -> invoke the super implementation of the method to actually
+ // create the bean instance.
+ if (BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
+ logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " +
+ "assignable to Spring's BeanFactoryPostProcessor interface. This will " +
+ "result in a failure to process annotations such as @Autowired, " +
+ "@Resource and @PostConstruct within the method's declaring " +
+ "@Configuration class. Add the 'static' modifier to this method to avoid " +
+ "these container lifecycle issues; see @Bean Javadoc for complete details",
+ beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
+ }
+ return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
- return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
+ else {
+ // the user (i.e. not the factory) is requesting this bean through a
+ // call to the bean method, direct or indirect. The bean may have already been
+ // marked as 'in creation' in certain autowiring scenarios; if so, temporarily
+ // set the in-creation status to false in order to avoid an exception.
+ boolean alreadyInCreation = this.beanFactory.isCurrentlyInCreation(beanName);
+ try {
+ if (alreadyInCreation) {
+ this.beanFactory.setCurrentlyInCreation(beanName, false);
+ }
+ return this.beanFactory.getBean(beanName);
+ } finally {
+ if (alreadyInCreation) {
+ this.beanFactory.setCurrentlyInCreation(beanName, true);
+ }
+ }
+ }
+
}
/**
@@ -266,7 +286,9 @@ public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object
* @return whether <var>beanName</var> already exists in the factory
*/
private boolean factoryContainsBean(String beanName) {
- return (this.beanFactory.containsBean(beanName) && !this.beanFactory.isCurrentlyInCreation(beanName));
+ boolean containsBean = this.beanFactory.containsBean(beanName);
+ boolean currentlyInCreation = this.beanFactory.isCurrentlyInCreation(beanName);
+ return (containsBean && !currentlyInCreation);
}
/** | true |
Other | spring-projects | spring-framework | 2afeb08e3c387715374c81a82074bae4235b5082.json | Fix @Autowired+@PostConstruct+@Configuration issue
A subtle issue existed with the way we relied on isCurrentlyInCreation
to determine whether a @Bean method is being called by the container
or by user code. This worked in most cases, but in the particular
scenario laid out by SPR-8080, this approach was no longer sufficient.
This change introduces a ThreadLocal that contains the factory method
currently being invoked by the container, such that enhanced @Bean
methods can check against it to see if they are being called by the
container or not. If so, that is the cue that the user-defined @Bean
method implementation should be invoked in order to actually create
the bean for the first time. If not, then the cached instance of
the already-created bean should be looked up and returned.
See ConfigurationClassPostConstructAndAutowiringTests for
reproduction cases and more detail.
Issue: SPR-8080 | org.springframework.context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java | @@ -0,0 +1,112 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import javax.annotation.PostConstruct;
+
+import org.junit.Test;
+import org.springframework.beans.TestBean;
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * Tests cornering the issue reported in SPR-8080. If the product of a @Bean method
+ * was @Autowired into a configuration class while at the same time the declaring
+ * configuration class for the @Bean method in question has a @PostConstruct
+ * (or other initializer) method, the container would become confused about the
+ * 'currently in creation' status of the autowired bean and result in creating multiple
+ * instances of the given @Bean, violating container scoping / singleton semantics.
+ *
+ * This is resolved through no longer relying on 'currently in creation' status, but
+ * rather on a thread local that informs the enhanced bean method implementation whether
+ * the factory is the caller or not.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+public class ConfigurationClassPostConstructAndAutowiringTests {
+
+ /**
+ * Prior to the fix for SPR-8080, this method would succeed due to ordering of
+ * configuration class registration.
+ */
+ @Test
+ public void control() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(Config1.class, Config2.class);
+ ctx.refresh();
+
+ assertions(ctx);
+
+ Config2 config2 = ctx.getBean(Config2.class);
+ assertThat(config2.testBean, is(ctx.getBean(TestBean.class)));
+ }
+
+ /**
+ * Prior to the fix for SPR-8080, this method would fail due to ordering of
+ * configuration class registration.
+ */
+ @Test
+ public void originalReproCase() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(Config2.class, Config1.class);
+ ctx.refresh();
+
+ assertions(ctx);
+ }
+
+ private void assertions(AnnotationConfigApplicationContext ctx) {
+ Config1 config1 = ctx.getBean(Config1.class);
+ TestBean testBean = ctx.getBean(TestBean.class);
+ assertThat(config1.beanMethodCallCount, is(1));
+ assertThat(testBean.getAge(), is(2));
+ }
+
+
+ @Configuration
+ static class Config1 {
+
+ int beanMethodCallCount = 0;
+
+ @PostConstruct
+ public void init() {
+ beanMethod().setAge(beanMethod().getAge() + 1); // age == 2
+ }
+
+ @Bean
+ public TestBean beanMethod() {
+ beanMethodCallCount++;
+ TestBean testBean = new TestBean();
+ testBean.setAge(1);
+ return testBean;
+ }
+ }
+
+
+ @Configuration
+ static class Config2 {
+ TestBean testBean;
+
+ @Autowired
+ void setTestBean(TestBean testBean) {
+ this.testBean = testBean;
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | 80f0eabbd93c83d00f8e2f02f529b1aba49a381a.json | Add MockEnvironment to .integration-tests | org.springframework.integration-tests/src/test/java/org/springframework/mock/env/MockEnvironment.java | @@ -0,0 +1,60 @@
+/*
+ * Copyright 2002-2011 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.mock.env;
+
+import org.springframework.core.env.AbstractEnvironment;
+import org.springframework.core.env.ConfigurableEnvironment;
+
+/**
+ * Simple {@link ConfigurableEnvironment} implementation exposing a
+ * {@link #setProperty(String, String)} and {@link #withProperty(String, String)}
+ * methods for testing purposes.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ * @see MockPropertySource
+ */
+public class MockEnvironment extends AbstractEnvironment {
+
+ private MockPropertySource propertySource = new MockPropertySource();
+
+ /**
+ * Create a new {@code MockEnvironment} with a single {@link MockPropertySource}.
+ */
+ public MockEnvironment() {
+ getPropertySources().addLast(propertySource);
+ }
+
+ /**
+ * Set a property on the underlying {@link MockPropertySource} for this environment.
+ */
+ public void setProperty(String key, String value) {
+ propertySource.setProperty(key, value);
+ }
+
+ /**
+ * Convenient synonym for {@link #setProperty} that returns the current instance.
+ * Useful for method chaining and fluent-style use.
+ * @return this {@link MockEnvironment} instance
+ * @see MockPropertySource#withProperty(String, String)
+ */
+ public MockEnvironment withProperty(String key, String value) {
+ this.setProperty(key, value);
+ return this;
+ }
+
+} | false |
Other | spring-projects | spring-framework | 52bef0b7b024e794186437dee78945fbb5bd209a.json | Allow static modifier on @Bean methods
Declaring @Bean methods as 'static' is now permitted, whereas previously
it raised an exception at @Configuration class validation time.
A static @Bean method can be called by the container without requiring
the instantiation of its declaring @Configuration class. This is
particularly useful when dealing with BeanFactoryPostProcessor beans,
as they can interfere with the standard post-processing lifecycle
necessary to handle @Autowired, @Inject, @Value, @PostConstruct and
other annotations.
static @Bean methods cannot recieve CGLIB enhancement for scoping and
AOP concerns. This is acceptable in BFPP cases as they rarely if ever
need it, and should not in typical cases ever be called by another
@Bean method. Once invoked by the container, the resulting bean will
be cached as usual, but multiple invocations of the static @Bean method
will result in creation of multiple instances of the bean.
static @Bean methods may not, for obvious reasons, refer to normal
instance @Bean methods, but again this is not likely a concern for BFPP
types. In the rare case that they do need a bean reference, parameter
injection into the static @Bean method is technically an option, but
should be avoided as it will potentially cause premature instantiation
of more beans that the user may have intended.
Note particularly that a WARN-level log message is now issued for any
non-static @Bean method with a return type assignable to BFPP. This
serves as a strong recommendation to users that they always mark BFPP
@Bean methods as static.
See @Bean Javadoc for complete details.
Issue: SPR-8257, SPR-8269 | org.springframework.context/src/main/java/org/springframework/context/annotation/Bean.java | @@ -37,8 +37,8 @@
*
* <p>While a {@link #name()} attribute is available, the default strategy for determining
* the name of a bean is to use the name of the Bean method. This is convenient and
- * intuitive, but if explicit naming is desired, the {@link #name()} attribute may be used.
- * Also note that {@link #name()} accepts an array of Strings. This is in order to allow
+ * intuitive, but if explicit naming is desired, the {@code name()} attribute may be used.
+ * Also note that {@code name()} accepts an array of Strings. This is in order to allow
* for specifying multiple names (i.e., aliases) for a single bean.
*
* <p>The <code>@Bean</code> annotation may be used on any methods in an <code>@Component</code>
@@ -56,6 +56,27 @@
* subclassing of each such configuration class at runtime. As a consequence, configuration
* classes and their factory methods must not be marked as final or private in this mode.
*
+ * <h3>A note on {@code BeanFactoryPostProcessor}-returning {@code @Bean} methods</h3>
+ * <p>Special consideration must be taken for {@code @Bean} methods that return Spring
+ * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessor}
+ * ({@code BFPP}) types. Because {@code BFPP} objects must be instantiated very early in the
+ * container lifecycle, they can interfere with processing of annotations such as {@code @Autowired},
+ * {@code @Value}, and {@code @PostConstruct} within {@code @Configuration} classes. To avoid these
+ * lifecycle issues, mark {@code BFPP}-returning {@code @Bean} methods as {@code static}. For example:
+ * <pre class="code">
+ * @Bean
+ * public static PropertyPlaceholderConfigurer ppc() {
+ * // instantiate, configure and return ppc ...
+ * }
+ * </pre>
+ * By marking this method as {@code static}, it can be invoked without causing instantiation of its
+ * declaring {@code @Configuration} class, thus avoiding the above-mentioned lifecycle conflicts.
+ * Note however that {@code static} {@code @Bean} methods will not be enhanced for scoping and AOP
+ * semantics as mentioned above. This works out in {@code BFPP} cases, as they are not typically
+ * referenced by other {@code @Bean} methods. As a reminder, a WARN-level log message will be
+ * issued for any non-static {@code @Bean} methods having a return type assignable to
+ * {@code BeanFactoryPostProcessor}.
+ *
* @author Rod Johnson
* @author Costin Leau
* @author Chris Beams | true |
Other | spring-projects | spring-framework | 52bef0b7b024e794186437dee78945fbb5bd209a.json | Allow static modifier on @Bean methods
Declaring @Bean methods as 'static' is now permitted, whereas previously
it raised an exception at @Configuration class validation time.
A static @Bean method can be called by the container without requiring
the instantiation of its declaring @Configuration class. This is
particularly useful when dealing with BeanFactoryPostProcessor beans,
as they can interfere with the standard post-processing lifecycle
necessary to handle @Autowired, @Inject, @Value, @PostConstruct and
other annotations.
static @Bean methods cannot recieve CGLIB enhancement for scoping and
AOP concerns. This is acceptable in BFPP cases as they rarely if ever
need it, and should not in typical cases ever be called by another
@Bean method. Once invoked by the container, the resulting bean will
be cached as usual, but multiple invocations of the static @Bean method
will result in creation of multiple instances of the bean.
static @Bean methods may not, for obvious reasons, refer to normal
instance @Bean methods, but again this is not likely a concern for BFPP
types. In the rare case that they do need a bean reference, parameter
injection into the static @Bean method is technically an option, but
should be avoided as it will potentially cause premature instantiation
of more beans that the user may have intended.
Note particularly that a WARN-level log message is now issued for any
non-static @Bean method with a return type assignable to BFPP. This
serves as a strong recommendation to users that they always mark BFPP
@Bean methods as static.
See @Bean Javadoc for complete details.
Issue: SPR-8257, SPR-8269 | org.springframework.context/src/main/java/org/springframework/context/annotation/BeanMethod.java | @@ -39,39 +39,25 @@ public BeanMethod(MethodMetadata metadata, ConfigurationClass configurationClass
@Override
public void validate(ProblemReporter problemReporter) {
+ if (getMetadata().isStatic()) {
+ // static @Bean methods have no constraints to validate -> return immediately
+ return;
+ }
+
if (this.configurationClass.getMetadata().isAnnotated(Configuration.class.getName())) {
if (!getMetadata().isOverridable()) {
+ // instance @Bean methods within @Configuration classes must be overridable to accommodate CGLIB
problemReporter.error(new NonOverridableMethodError());
}
}
- else {
- if (getMetadata().isStatic()) {
- problemReporter.error(new StaticMethodError());
- }
- }
}
- /**
- * {@link Bean} methods must be overridable in order to accommodate CGLIB.
- */
+
private class NonOverridableMethodError extends Problem {
public NonOverridableMethodError() {
- super(String.format("Method '%s' must not be private, final or static; change the method's modifiers to continue",
- getMetadata().getMethodName()), getResourceLocation());
- }
- }
-
-
- /**
- * {@link Bean} methods must at least not be static in the non-CGLIB case.
- */
- private class StaticMethodError extends Problem {
-
- public StaticMethodError() {
- super(String.format("Method '%s' must not be static; remove the method's static modifier to continue",
+ super(String.format("@Bean method '%s' must not be private or final; change the method's modifiers to continue",
getMetadata().getMethodName()), getResourceLocation());
}
}
-
} | true |
Other | spring-projects | spring-framework | 52bef0b7b024e794186437dee78945fbb5bd209a.json | Allow static modifier on @Bean methods
Declaring @Bean methods as 'static' is now permitted, whereas previously
it raised an exception at @Configuration class validation time.
A static @Bean method can be called by the container without requiring
the instantiation of its declaring @Configuration class. This is
particularly useful when dealing with BeanFactoryPostProcessor beans,
as they can interfere with the standard post-processing lifecycle
necessary to handle @Autowired, @Inject, @Value, @PostConstruct and
other annotations.
static @Bean methods cannot recieve CGLIB enhancement for scoping and
AOP concerns. This is acceptable in BFPP cases as they rarely if ever
need it, and should not in typical cases ever be called by another
@Bean method. Once invoked by the container, the resulting bean will
be cached as usual, but multiple invocations of the static @Bean method
will result in creation of multiple instances of the bean.
static @Bean methods may not, for obvious reasons, refer to normal
instance @Bean methods, but again this is not likely a concern for BFPP
types. In the rare case that they do need a bean reference, parameter
injection into the static @Bean method is technically an option, but
should be avoided as it will potentially cause premature instantiation
of more beans that the user may have intended.
Note particularly that a WARN-level log message is now issued for any
non-static @Bean method with a return type assignable to BFPP. This
serves as a strong recommendation to users that they always mark BFPP
@Bean methods as static.
See @Bean Javadoc for complete details.
Issue: SPR-8257, SPR-8269 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java | @@ -162,8 +162,16 @@ private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
RootBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass);
beanDef.setResource(configClass.getResource());
beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
- beanDef.setFactoryBeanName(configClass.getBeanName());
- beanDef.setUniqueFactoryMethodName(metadata.getMethodName());
+ if (metadata.isStatic()) {
+ // static @Bean method
+ beanDef.setBeanClassName(configClass.getMetadata().getClassName());
+ beanDef.setFactoryMethodName(metadata.getMethodName());
+ }
+ else {
+ // instance @Bean method
+ beanDef.setFactoryBeanName(configClass.getBeanName());
+ beanDef.setUniqueFactoryMethodName(metadata.getMethodName());
+ }
beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);
| true |
Other | spring-projects | spring-framework | 52bef0b7b024e794186437dee78945fbb5bd209a.json | Allow static modifier on @Bean methods
Declaring @Bean methods as 'static' is now permitted, whereas previously
it raised an exception at @Configuration class validation time.
A static @Bean method can be called by the container without requiring
the instantiation of its declaring @Configuration class. This is
particularly useful when dealing with BeanFactoryPostProcessor beans,
as they can interfere with the standard post-processing lifecycle
necessary to handle @Autowired, @Inject, @Value, @PostConstruct and
other annotations.
static @Bean methods cannot recieve CGLIB enhancement for scoping and
AOP concerns. This is acceptable in BFPP cases as they rarely if ever
need it, and should not in typical cases ever be called by another
@Bean method. Once invoked by the container, the resulting bean will
be cached as usual, but multiple invocations of the static @Bean method
will result in creation of multiple instances of the bean.
static @Bean methods may not, for obvious reasons, refer to normal
instance @Bean methods, but again this is not likely a concern for BFPP
types. In the rare case that they do need a bean reference, parameter
injection into the static @Bean method is technically an option, but
should be avoided as it will potentially cause premature instantiation
of more beans that the user may have intended.
Note particularly that a WARN-level log message is now issued for any
non-static @Bean method with a return type assignable to BFPP. This
serves as a strong recommendation to users that they always mark BFPP
@Bean methods as static.
See @Bean Javadoc for complete details.
Issue: SPR-8257, SPR-8269 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java | @@ -33,6 +33,7 @@
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
@@ -239,6 +240,15 @@ public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object
return this.beanFactory.getBean(beanName);
}
+ if (BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
+ logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " +
+ "assignable to Spring's BeanFactoryPostProcessor interface. This will " +
+ "result in a failure to process annotations such as @Autowired, " +
+ "@Resource and @PostConstruct within the method's declaring " +
+ "@Configuration class. Add the 'static' modifier to this method to avoid" +
+ "these container lifecycle issues; see @Bean Javadoc for complete details",
+ beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
+ }
return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
| true |
Other | spring-projects | spring-framework | 52bef0b7b024e794186437dee78945fbb5bd209a.json | Allow static modifier on @Bean methods
Declaring @Bean methods as 'static' is now permitted, whereas previously
it raised an exception at @Configuration class validation time.
A static @Bean method can be called by the container without requiring
the instantiation of its declaring @Configuration class. This is
particularly useful when dealing with BeanFactoryPostProcessor beans,
as they can interfere with the standard post-processing lifecycle
necessary to handle @Autowired, @Inject, @Value, @PostConstruct and
other annotations.
static @Bean methods cannot recieve CGLIB enhancement for scoping and
AOP concerns. This is acceptable in BFPP cases as they rarely if ever
need it, and should not in typical cases ever be called by another
@Bean method. Once invoked by the container, the resulting bean will
be cached as usual, but multiple invocations of the static @Bean method
will result in creation of multiple instances of the bean.
static @Bean methods may not, for obvious reasons, refer to normal
instance @Bean methods, but again this is not likely a concern for BFPP
types. In the rare case that they do need a bean reference, parameter
injection into the static @Bean method is technically an option, but
should be avoided as it will potentially cause premature instantiation
of more beans that the user may have intended.
Note particularly that a WARN-level log message is now issued for any
non-static @Bean method with a return type assignable to BFPP. This
serves as a strong recommendation to users that they always mark BFPP
@Bean methods as static.
See @Bean Javadoc for complete details.
Issue: SPR-8257, SPR-8269 | org.springframework.context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java | @@ -0,0 +1,122 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.junit.Assert.assertThat;
+
+import org.junit.Test;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.TestBean;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+
+/**
+ * Tests semantics of declaring {@link BeanFactoryPostProcessor}-returning @Bean
+ * methods, specifically as regards static @Bean methods and the avoidance of
+ * container lifecycle issues when BFPPs are in the mix.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+public class ConfigurationClassAndBFPPTests {
+
+ @Test
+ public void autowiringFailsWithBFPPAsInstanceMethod() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsInstanceMethod.class);
+ ctx.refresh();
+ // instance method BFPP interferes with lifecycle -> autowiring fails!
+ // WARN-level logging should have been issued about returning BFPP from non-static @Bean method
+ assertThat(ctx.getBean(AutowiredConfigWithBFPPAsInstanceMethod.class).autowiredTestBean, nullValue());
+ }
+
+ @Test
+ public void autowiringSucceedsWithBFPPAsStaticMethod() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsStaticMethod.class);
+ ctx.refresh();
+ // static method BFPP does not interfere with lifecycle -> autowiring succeeds
+ assertThat(ctx.getBean(AutowiredConfigWithBFPPAsStaticMethod.class).autowiredTestBean, notNullValue());
+ }
+
+
+ @Configuration
+ static class TestBeanConfig {
+ @Bean
+ public TestBean testBean() {
+ return new TestBean();
+ }
+ }
+
+
+ @Configuration
+ static class AutowiredConfigWithBFPPAsInstanceMethod {
+ @Autowired TestBean autowiredTestBean;
+
+ @Bean
+ public BeanFactoryPostProcessor bfpp() {
+ return new BeanFactoryPostProcessor() {
+ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ // no-op
+ }
+ };
+ }
+ }
+
+
+ @Configuration
+ static class AutowiredConfigWithBFPPAsStaticMethod {
+ @Autowired TestBean autowiredTestBean;
+
+ @Bean
+ public static final BeanFactoryPostProcessor bfpp() {
+ return new BeanFactoryPostProcessor() {
+ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ // no-op
+ }
+ };
+ }
+ }
+
+
+ @Test
+ @SuppressWarnings("static-access")
+ public void staticBeanMethodsDoNotRespectScoping() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(ConfigWithStaticBeanMethod.class);
+ ctx.refresh();
+
+ ConfigWithStaticBeanMethod config = ctx.getBean(ConfigWithStaticBeanMethod.class);
+ assertThat(config.testBean(), not(sameInstance(config.testBean())));
+ }
+
+
+ @Configuration
+ static class ConfigWithStaticBeanMethod {
+ @Bean
+ public static TestBean testBean() {
+ return new TestBean("foo");
+ }
+ }
+
+
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/CircularComponentScanException.java | @@ -0,0 +1,32 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+/**
+ * Exception thrown upon detection of circular {@link ComponentScan} use.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+@SuppressWarnings("serial")
+class CircularComponentScanException extends IllegalStateException {
+
+ public CircularComponentScanException(String message, Exception cause) {
+ super(message, cause);
+ }
+
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java | @@ -269,7 +269,7 @@ protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, Bea
* @return <code>true</code> if the bean can be registered as-is;
* <code>false</code> if it should be skipped because there is an
* existing, compatible bean definition for the specified name
- * @throws IllegalStateException if an existing, incompatible
+ * @throws ConflictingBeanDefinitionException if an existing, incompatible
* bean definition has been found for the specified name
*/
protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
@@ -284,7 +284,7 @@ protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition)
if (isCompatible(beanDefinition, existingDef)) {
return false;
}
- throw new IllegalStateException("Annotation-specified bean name '" + beanName +
+ throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName +
"' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " +
"non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");
} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java | @@ -20,14 +20,15 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
-import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
@@ -54,15 +55,9 @@ public ComponentScanAnnotationParser(ResourceLoader resourceLoader, Environment
this.registry = registry;
}
- public void parse(AnnotationMetadata annotationMetadata) {
- Map<String, Object> attribs = annotationMetadata.getAnnotationAttributes(ComponentScan.class.getName());
- if (attribs == null) {
- // @ComponentScan annotation is not present -> do nothing
- return;
- }
-
+ public Set<BeanDefinitionHolder> parse(Map<String, Object> componentScanAttributes) {
ClassPathBeanDefinitionScanner scanner =
- new ClassPathBeanDefinitionScanner(registry, (Boolean)attribs.get("useDefaultFilters"));
+ new ClassPathBeanDefinitionScanner(registry, (Boolean)componentScanAttributes.get("useDefaultFilters"));
Assert.notNull(this.environment, "Environment must not be null");
scanner.setEnvironment(this.environment);
@@ -71,37 +66,37 @@ public void parse(AnnotationMetadata annotationMetadata) {
scanner.setResourceLoader(this.resourceLoader);
scanner.setBeanNameGenerator(BeanUtils.instantiateClass(
- (Class<?>)attribs.get("nameGenerator"), BeanNameGenerator.class));
+ (Class<?>)componentScanAttributes.get("nameGenerator"), BeanNameGenerator.class));
- ScopedProxyMode scopedProxyMode = (ScopedProxyMode) attribs.get("scopedProxy");
+ ScopedProxyMode scopedProxyMode = (ScopedProxyMode) componentScanAttributes.get("scopedProxy");
if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
scanner.setScopedProxyMode(scopedProxyMode);
} else {
scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(
- (Class<?>)attribs.get("scopeResolver"), ScopeMetadataResolver.class));
+ (Class<?>)componentScanAttributes.get("scopeResolver"), ScopeMetadataResolver.class));
}
- scanner.setResourcePattern((String)attribs.get("resourcePattern"));
+ scanner.setResourcePattern((String)componentScanAttributes.get("resourcePattern"));
- for (Filter filter : (Filter[])attribs.get("includeFilters")) {
+ for (Filter filter : (Filter[])componentScanAttributes.get("includeFilters")) {
scanner.addIncludeFilter(createTypeFilter(filter));
}
- for (Filter filter : (Filter[])attribs.get("excludeFilters")) {
+ for (Filter filter : (Filter[])componentScanAttributes.get("excludeFilters")) {
scanner.addExcludeFilter(createTypeFilter(filter));
}
List<String> basePackages = new ArrayList<String>();
- for (String pkg : (String[])attribs.get("value")) {
+ for (String pkg : (String[])componentScanAttributes.get("value")) {
if (StringUtils.hasText(pkg)) {
basePackages.add(pkg);
}
}
- for (String pkg : (String[])attribs.get("basePackages")) {
+ for (String pkg : (String[])componentScanAttributes.get("basePackages")) {
if (StringUtils.hasText(pkg)) {
basePackages.add(pkg);
}
}
- for (Class<?> clazz : (Class<?>[])attribs.get("basePackageClasses")) {
+ for (Class<?> clazz : (Class<?>[])componentScanAttributes.get("basePackageClasses")) {
// TODO: loading user types directly here. implications on load-time
// weaving may mean we need to revert to stringified class names in
// annotation metadata
@@ -112,7 +107,7 @@ public void parse(AnnotationMetadata annotationMetadata) {
throw new IllegalStateException("At least one base package must be specified");
}
- scanner.scan(basePackages.toArray(new String[]{}));
+ return scanner.doScan(basePackages.toArray(new String[]{}));
}
private TypeFilter createTypeFilter(Filter filter) { | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java | @@ -27,7 +27,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor;
@@ -44,19 +43,12 @@
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
-import org.springframework.context.EnvironmentAware;
-import org.springframework.context.ResourceLoaderAware;
-import org.springframework.core.Conventions;
-import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
-import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
-import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
-import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
@@ -74,15 +66,8 @@
*/
public class ConfigurationClassBeanDefinitionReader {
- private static final String CONFIGURATION_CLASS_FULL = "full";
-
- private static final String CONFIGURATION_CLASS_LITE = "lite";
-
- private static final String CONFIGURATION_CLASS_ATTRIBUTE =
- Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
-
private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class);
-
+
private final BeanDefinitionRegistry registry;
private final SourceExtractor sourceExtractor;
@@ -93,28 +78,21 @@ public class ConfigurationClassBeanDefinitionReader {
private ResourceLoader resourceLoader;
- private Environment environment;
-
- private final ComponentScanAnnotationParser componentScanParser;
-
/**
* Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
* to populate the given {@link BeanDefinitionRegistry}.
* @param problemReporter
* @param metadataReaderFactory
*/
- public ConfigurationClassBeanDefinitionReader(final BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
+ public ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
ProblemReporter problemReporter, MetadataReaderFactory metadataReaderFactory,
- ResourceLoader resourceLoader, Environment environment) {
+ ResourceLoader resourceLoader) {
this.registry = registry;
this.sourceExtractor = sourceExtractor;
this.problemReporter = problemReporter;
this.metadataReaderFactory = metadataReaderFactory;
this.resourceLoader = resourceLoader;
- this.environment = environment;
-
- this.componentScanParser = new ComponentScanAnnotationParser(resourceLoader, environment, registry);
}
@@ -133,8 +111,6 @@ public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
* class itself, all its {@link Bean} methods
*/
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
- AnnotationMetadata metadata = configClass.getMetadata();
- componentScanParser.parse(metadata);
doLoadBeanDefinitionForConfigurationClassIfNecessary(configClass);
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
loadBeanDefinitionsForBeanMethod(beanMethod);
@@ -155,7 +131,7 @@ private void doLoadBeanDefinitionForConfigurationClassIfNecessary(ConfigurationC
BeanDefinition configBeanDef = new GenericBeanDefinition();
String className = configClass.getMetadata().getClassName();
configBeanDef.setBeanClassName(className);
- if (checkConfigurationClassCandidate(configBeanDef, this.metadataReaderFactory)) {
+ if (ConfigurationClassUtils.checkConfigurationClassCandidate(configBeanDef, this.metadataReaderFactory)) {
String configBeanName = BeanDefinitionReaderUtils.registerWithGeneratedName((AbstractBeanDefinition)configBeanDef, this.registry);
configClass.setBeanName(configBeanName);
if (logger.isDebugEnabled()) {
@@ -311,59 +287,6 @@ private void loadBeanDefinitionsFromImportedResources(Map<String, Class<?>> impo
}
- /**
- * Check whether the given bean definition is a candidate for a configuration class,
- * and mark it accordingly.
- * @param beanDef the bean definition to check
- * @param metadataReaderFactory the current factory in use by the caller
- * @return whether the candidate qualifies as (any kind of) configuration class
- */
- public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
- AnnotationMetadata metadata = null;
-
- // Check already loaded Class if present...
- // since we possibly can't even load the class file for this Class.
- if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
- metadata = new StandardAnnotationMetadata(((AbstractBeanDefinition) beanDef).getBeanClass());
- }
- else {
- String className = beanDef.getBeanClassName();
- if (className != null) {
- try {
- MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
- metadata = metadataReader.getAnnotationMetadata();
- }
- catch (IOException ex) {
- if (logger.isDebugEnabled()) {
- logger.debug("Could not find class file for introspecting factory methods: " + className, ex);
- }
- return false;
- }
- }
- }
-
- if (metadata != null) {
- if (metadata.isAnnotated(Configuration.class.getName())) {
- beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
- return true;
- }
- else if (metadata.isAnnotated(Component.class.getName()) ||
- metadata.hasAnnotatedMethods(Bean.class.getName())) {
- beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
- return true;
- }
- }
- return false;
- }
-
- /**
- * Determine whether the given bean definition indicates a full @Configuration class.
- */
- public static boolean isFullConfigurationClass(BeanDefinition beanDef) {
- return CONFIGURATION_CLASS_FULL.equals(beanDef.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE));
- }
-
-
/**
* {@link RootBeanDefinition} marker subclass used to signify that a bean definition
* was created from a configuration class as opposed to any other configuration source. | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java | @@ -28,11 +28,14 @@
import java.util.Stack;
import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.parsing.Location;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.beans.factory.parsing.ProblemReporter;
+import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
+import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
@@ -72,16 +75,24 @@ class ConfigurationClassParser {
private final Environment environment;
+ private final ResourceLoader resourceLoader;
+
+ private final ComponentScanAnnotationParser componentScanParser;
+
/**
* Create a new {@link ConfigurationClassParser} instance that will be used
* to populate the set of configuration classes.
*/
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
- ProblemReporter problemReporter, Environment environment) {
+ ProblemReporter problemReporter, Environment environment,
+ ResourceLoader resourceLoader, BeanDefinitionRegistry registry) {
this.metadataReaderFactory = metadataReaderFactory;
this.problemReporter = problemReporter;
this.environment = environment;
+ this.resourceLoader = resourceLoader;
+
+ this.componentScanParser = new ComponentScanAnnotationParser(this.resourceLoader, this.environment, registry);
}
@@ -141,6 +152,25 @@ protected void processConfigurationClass(ConfigurationClass configClass) throws
}
protected void doProcessConfigurationClass(ConfigurationClass configClass, AnnotationMetadata metadata) throws IOException {
+ Map<String, Object> componentScanAttributes = metadata.getAnnotationAttributes(ComponentScan.class.getName());
+ if (componentScanAttributes != null) {
+ // the config class is annotated with @ComponentScan -> perform the scan immediately
+ Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScanAttributes);
+
+ // check the set of scanned definitions for any further config classes and parse recursively if necessary
+ for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
+ if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), metadataReaderFactory)) {
+ try {
+ this.parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
+ } catch (ConflictingBeanDefinitionException ex) {
+ throw new CircularComponentScanException(
+ "A conflicting bean definition was detected while processing @ComponentScan annotations. " +
+ "This usually indicates a circle between scanned packages.", ex);
+ }
+ }
+ }
+ }
+
List<Map<String, Object>> allImportAttribs =
AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
for (Map<String, Object> importAttribs : allImportAttribs) { | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java | @@ -193,15 +193,16 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
*/
private void processConfigurationClasses(BeanDefinitionRegistry registry) {
ConfigurationClassBeanDefinitionReader reader = getConfigurationClassBeanDefinitionReader(registry);
- ConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment);
+ ConfigurationClassParser parser = new ConfigurationClassParser(
+ this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, registry);
processConfigBeanDefinitions(parser, reader, registry);
enhanceConfigurationClasses((ConfigurableListableBeanFactory)registry);
}
private ConfigurationClassBeanDefinitionReader getConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry) {
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
- registry, this.sourceExtractor, this.problemReporter, this.metadataReaderFactory, this.resourceLoader, this.environment);
+ registry, this.sourceExtractor, this.problemReporter, this.metadataReaderFactory, this.resourceLoader);
}
return this.reader;
}
@@ -214,7 +215,7 @@ public void processConfigBeanDefinitions(ConfigurationClassParser parser, Config
Set<BeanDefinitionHolder> configCandidates = new LinkedHashSet<BeanDefinitionHolder>();
for (String beanName : registry.getBeanDefinitionNames()) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
- if (ConfigurationClassBeanDefinitionReader.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
+ if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
@@ -262,7 +263,7 @@ public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFact
Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<String, AbstractBeanDefinition>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
- if (ConfigurationClassBeanDefinitionReader.isFullConfigurationClass(beanDef)) {
+ if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
if (!(beanDef instanceof AbstractBeanDefinition)) {
throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
beanName + "' since it is not stored in an AbstractBeanDefinition subclass"); | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java | @@ -0,0 +1,102 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.beans.factory.support.AbstractBeanDefinition;
+import org.springframework.core.Conventions;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.StandardAnnotationMetadata;
+import org.springframework.core.type.classreading.MetadataReader;
+import org.springframework.core.type.classreading.MetadataReaderFactory;
+import org.springframework.stereotype.Component;
+
+/**
+ * Utilities for processing @{@link Configuration} classes.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+abstract class ConfigurationClassUtils {
+
+ private static final Log logger = LogFactory.getLog(ConfigurationClassUtils.class);
+
+ private static final String CONFIGURATION_CLASS_FULL = "full";
+
+ private static final String CONFIGURATION_CLASS_LITE = "lite";
+
+ private static final String CONFIGURATION_CLASS_ATTRIBUTE =
+ Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
+
+
+ /**
+ * Check whether the given bean definition is a candidate for a configuration class,
+ * and mark it accordingly.
+ * @param beanDef the bean definition to check
+ * @param metadataReaderFactory the current factory in use by the caller
+ * @return whether the candidate qualifies as (any kind of) configuration class
+ */
+ public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
+ AnnotationMetadata metadata = null;
+
+ // Check already loaded Class if present...
+ // since we possibly can't even load the class file for this Class.
+ if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
+ metadata = new StandardAnnotationMetadata(((AbstractBeanDefinition) beanDef).getBeanClass());
+ }
+ else {
+ String className = beanDef.getBeanClassName();
+ if (className != null) {
+ try {
+ MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
+ metadata = metadataReader.getAnnotationMetadata();
+ }
+ catch (IOException ex) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Could not find class file for introspecting factory methods: " + className, ex);
+ }
+ return false;
+ }
+ }
+ }
+
+ if (metadata != null) {
+ if (metadata.isAnnotated(Configuration.class.getName())) {
+ beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
+ return true;
+ }
+ else if (metadata.isAnnotated(Component.class.getName()) ||
+ metadata.hasAnnotatedMethods(Bean.class.getName())) {
+ beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Determine whether the given bean definition indicates a full @Configuration class.
+ */
+ public static boolean isFullConfigurationClass(BeanDefinition beanDef) {
+ return CONFIGURATION_CLASS_FULL.equals(beanDef.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE));
+ }
+
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConflictingBeanDefinitionException.java | @@ -0,0 +1,33 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+/**
+ * Marker subclass of {@link IllegalStateException}, allowing for explicit
+ * catch clauses in calling code.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+@SuppressWarnings("serial")
+class ConflictingBeanDefinitionException extends IllegalStateException {
+
+ public ConflictingBeanDefinitionException(String message) {
+ super(message);
+ }
+
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/AsmCircularImportDetectionTests.java | @@ -16,7 +16,9 @@
package org.springframework.context.annotation;
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
+import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.env.DefaultEnvironment;
+import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
/**
@@ -33,7 +35,12 @@ public class AsmCircularImportDetectionTests extends AbstractCircularImportDetec
@Override
protected ConfigurationClassParser newParser() {
- return new ConfigurationClassParser(new CachingMetadataReaderFactory(), new FailFastProblemReporter(), new DefaultEnvironment());
+ return new ConfigurationClassParser(
+ new CachingMetadataReaderFactory(),
+ new FailFastProblemReporter(),
+ new DefaultEnvironment(),
+ new DefaultResourceLoader(),
+ new DefaultListableBeanFactory());
}
@Override | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationRecursionTests.java | @@ -0,0 +1,60 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.junit.Assert.assertThat;
+
+import org.junit.Test;
+import org.springframework.context.annotation.componentscan.cycle.left.LeftConfig;
+import org.springframework.context.annotation.componentscan.level1.Level1Config;
+import org.springframework.context.annotation.componentscan.level2.Level2Config;
+import org.springframework.context.annotation.componentscan.level3.Level3Component;
+
+/**
+ * Tests ensuring that configuration clasess marked with @ComponentScan
+ * may be processed recursively
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+public class ComponentScanAnnotationRecursionTests {
+
+ @Test
+ public void recursion() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(Level1Config.class);
+ ctx.refresh();
+
+ // assert that all levels have been detected
+ ctx.getBean(Level1Config.class);
+ ctx.getBean(Level2Config.class);
+ ctx.getBean(Level3Component.class);
+
+ // assert that enhancement is working
+ assertThat(ctx.getBean("level1Bean"), sameInstance(ctx.getBean("level1Bean")));
+ assertThat(ctx.getBean("level2Bean"), sameInstance(ctx.getBean("level2Bean")));
+ }
+
+ @Test(expected=CircularComponentScanException.class)
+ public void cycleDetection() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(LeftConfig.class);
+ ctx.refresh();
+ }
+
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/cycle/left/LeftConfig.java | @@ -0,0 +1,26 @@
+/*
+ * Copyright 2002-2011 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.context.annotation.componentscan.cycle.left;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan("org.springframework.context.annotation.componentscan.cycle.right")
+public class LeftConfig {
+
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/cycle/right/RightConfig.java | @@ -0,0 +1,26 @@
+/*
+ * Copyright 2002-2011 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.context.annotation.componentscan.cycle.right;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan("org.springframework.context.annotation.componentscan.cycle.left")
+public class RightConfig {
+
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/level1/Level1Config.java | @@ -0,0 +1,31 @@
+/*
+ * Copyright 2002-2011 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.context.annotation.componentscan.level1;
+
+import org.springframework.beans.TestBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan("org.springframework.context.annotation.componentscan.level2")
+public class Level1Config {
+ @Bean
+ public TestBean level1Bean() {
+ return new TestBean("level1Bean");
+ }
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/level2/Level2Config.java | @@ -0,0 +1,31 @@
+/*
+ * Copyright 2002-2011 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.context.annotation.componentscan.level2;
+
+import org.springframework.beans.TestBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan("org.springframework.context.annotation.componentscan.level3")
+public class Level2Config {
+ @Bean
+ public TestBean level2Bean() {
+ return new TestBean("level2Bean");
+ }
+} | true |
Other | spring-projects | spring-framework | d0c31ad84cffd7af718a45d679483a1c51f9e552.json | Allow recursive use of @ComponentScan
Prior to this change, @ComponentScan annotations were only processed at
the first level of depth. Now, the set of bean definitions resulting
from each declaration of @ComponentScan is checked for configuration
classes that declare @ComponentScan, and recursion is performed as
necessary.
Cycles between @ComponentScan declarations are detected as well. See
CircularComponentScanException.
Issue: SPR-8307 | org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/level3/Level3Component.java | @@ -0,0 +1,24 @@
+/*
+ * Copyright 2002-2011 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.context.annotation.componentscan.level3;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class Level3Component {
+
+} | true |
Other | spring-projects | spring-framework | 4f7bdbd3de8e1ca91ad84ea41afc4f525e1b4fd8.json | Make ConfigurationClassBeanDefinitionReader public
Issue: SPR-8200 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java | @@ -73,7 +73,7 @@
* @since 3.0
* @see ConfigurationClassParser
*/
-class ConfigurationClassBeanDefinitionReader {
+public class ConfigurationClassBeanDefinitionReader {
private static final String CONFIGURATION_CLASS_FULL = "full";
| false |
Other | spring-projects | spring-framework | 6f80578a387098bcf054249c512025ec81ae182b.json | Ignore fragile test dependent on debug symbols
Issue: SPR-8078 | org.springframework.core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java | @@ -25,6 +25,7 @@
import junit.framework.TestCase;
+import org.junit.Ignore;
import org.springframework.beans.TestBean;
/**
@@ -192,7 +193,12 @@ public void testGenerifiedClass() throws Exception {
//System.in.read();
}
- public void testMemUsage() throws Exception {
+ /**
+ * Ignored because Ubuntu packages OpenJDK with debug symbols enabled.
+ * See SPR-8078.
+ */
+ @Ignore
+ public void ignore_testClassesWithoutDebugSymbols() throws Exception {
// JDK classes don't have debug information (usually)
Class clazz = Component.class;
String methodName = "list"; | false |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.beans/src/main/java/org/springframework/beans/PropertyEditorRegistry.java | @@ -39,7 +39,7 @@ public interface PropertyEditorRegistry {
* @param requiredType the type of the property
* @param propertyEditor the editor to register
*/
- void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor);
+ void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor);
/**
* Register the given custom property editor for the given type and
@@ -64,7 +64,7 @@ public interface PropertyEditorRegistry {
* <code>null</code> if registering an editor for all properties of the given type
* @param propertyEditor editor to register
*/
- void registerCustomEditor(Class requiredType, String propertyPath, PropertyEditor propertyEditor);
+ void registerCustomEditor(Class<?> requiredType, String propertyPath, PropertyEditor propertyEditor);
/**
* Find a custom property editor for the given type and property.
@@ -74,6 +74,6 @@ public interface PropertyEditorRegistry {
* <code>null</code> if looking for an editor for all properties of the given type
* @return the registered editor, or <code>null</code> if none
*/
- PropertyEditor findCustomEditor(Class requiredType, String propertyPath);
+ PropertyEditor findCustomEditor(Class<?> requiredType, String propertyPath);
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/AbstractBindingResult.java | @@ -41,6 +41,7 @@
* @since 2.0
* @see Errors
*/
+@SuppressWarnings("serial")
public abstract class AbstractBindingResult extends AbstractErrors implements BindingResult, Serializable {
private final String objectName;
@@ -131,7 +132,7 @@ public String[] resolveMessageCodes(String errorCode) {
}
public String[] resolveMessageCodes(String errorCode, String field) {
- Class fieldType = getFieldType(field);
+ Class<?> fieldType = getFieldType(field);
return getMessageCodesResolver().resolveMessageCodes(
errorCode, getObjectName(), fixedField(field), fieldType);
}
@@ -237,7 +238,7 @@ public Object getFieldValue(String field) {
* @see #getActualFieldValue
*/
@Override
- public Class getFieldType(String field) {
+ public Class<?> getFieldType(String field) {
Object value = getActualFieldValue(fixedField(field));
if (value != null) {
return value.getClass();
@@ -286,10 +287,10 @@ public Object getRawFieldValue(String field) {
* {@link #getPropertyEditorRegistry() PropertyEditorRegistry}'s
* editor lookup facility, if available.
*/
- public PropertyEditor findEditor(String field, Class valueType) {
+ public PropertyEditor findEditor(String field, Class<?> valueType) {
PropertyEditorRegistry editorRegistry = getPropertyEditorRegistry();
if (editorRegistry != null) {
- Class valueTypeToUse = valueType;
+ Class<?> valueTypeToUse = valueType;
if (valueTypeToUse == null) {
valueTypeToUse = getFieldType(field);
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/AbstractErrors.java | @@ -33,6 +33,7 @@
* @author Juergen Hoeller
* @since 2.5.3
*/
+@SuppressWarnings("serial")
public abstract class AbstractErrors implements Errors, Serializable {
private String nestedPath = "";
@@ -146,8 +147,8 @@ public int getGlobalErrorCount() {
}
public ObjectError getGlobalError() {
- List globalErrors = getGlobalErrors();
- return (!globalErrors.isEmpty() ? (ObjectError) globalErrors.get(0) : null);
+ List<ObjectError> globalErrors = getGlobalErrors();
+ return (!globalErrors.isEmpty() ? globalErrors.get(0) : null);
}
public boolean hasFieldErrors() {
@@ -159,8 +160,8 @@ public int getFieldErrorCount() {
}
public FieldError getFieldError() {
- List fieldErrors = getFieldErrors();
- return (!fieldErrors.isEmpty() ? (FieldError) fieldErrors.get(0) : null);
+ List<FieldError> fieldErrors = getFieldErrors();
+ return (!fieldErrors.isEmpty() ? fieldErrors.get(0) : null);
}
public boolean hasFieldErrors(String field) {
@@ -184,12 +185,12 @@ public List<FieldError> getFieldErrors(String field) {
}
public FieldError getFieldError(String field) {
- List fieldErrors = getFieldErrors(field);
+ List<FieldError> fieldErrors = getFieldErrors(field);
return (!fieldErrors.isEmpty() ? (FieldError) fieldErrors.get(0) : null);
}
- public Class getFieldType(String field) {
+ public Class<?> getFieldType(String field) {
Object value = getFieldValue(field);
if (value != null) {
return value.getClass(); | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/AbstractPropertyBindingResult.java | @@ -39,6 +39,7 @@
* @see org.springframework.beans.PropertyAccessor
* @see org.springframework.beans.ConfigurablePropertyAccessor
*/
+@SuppressWarnings("serial")
public abstract class AbstractPropertyBindingResult extends AbstractBindingResult {
private ConversionService conversionService;
@@ -85,7 +86,7 @@ protected String canonicalFieldName(String field) {
* @see #getPropertyAccessor()
*/
@Override
- public Class getFieldType(String field) {
+ public Class<?> getFieldType(String field) {
return getPropertyAccessor().getPropertyType(fixedField(field));
}
@@ -133,7 +134,7 @@ protected Object formatFieldValue(String field, Object value) {
* @return the custom PropertyEditor, or <code>null</code>
*/
protected PropertyEditor getCustomEditor(String fixedField) {
- Class targetType = getPropertyAccessor().getPropertyType(fixedField);
+ Class<?> targetType = getPropertyAccessor().getPropertyType(fixedField);
PropertyEditor editor = getPropertyAccessor().findCustomEditor(targetType, fixedField);
if (editor == null) {
editor = BeanUtils.findEditorByConvention(targetType);
@@ -146,8 +147,8 @@ protected PropertyEditor getCustomEditor(String fixedField) {
* if applicable.
*/
@Override
- public PropertyEditor findEditor(String field, Class valueType) {
- Class valueTypeForLookup = valueType;
+ public PropertyEditor findEditor(String field, Class<?> valueType) {
+ Class<?> valueTypeForLookup = valueType;
if (valueTypeForLookup == null) {
valueTypeForLookup = getFieldType(field);
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/BeanPropertyBindingResult.java | @@ -40,6 +40,7 @@
* @see DataBinder#initBeanPropertyAccess()
* @see DirectFieldBindingResult
*/
+@SuppressWarnings("serial")
public class BeanPropertyBindingResult extends AbstractPropertyBindingResult implements Serializable {
private final Object target; | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/BindException.java | @@ -40,6 +40,7 @@
* @see DataBinder#getBindingResult()
* @see DataBinder#close()
*/
+@SuppressWarnings("serial")
public class BindException extends Exception implements BindingResult {
private final BindingResult bindingResult;
@@ -134,7 +135,7 @@ public int getErrorCount() {
return this.bindingResult.getErrorCount();
}
- public List getAllErrors() {
+ public List<ObjectError> getAllErrors() {
return this.bindingResult.getAllErrors();
}
@@ -146,7 +147,7 @@ public int getGlobalErrorCount() {
return this.bindingResult.getGlobalErrorCount();
}
- public List getGlobalErrors() {
+ public List<ObjectError> getGlobalErrors() {
return this.bindingResult.getGlobalErrors();
}
@@ -162,7 +163,7 @@ public int getFieldErrorCount() {
return this.bindingResult.getFieldErrorCount();
}
- public List getFieldErrors() {
+ public List<FieldError> getFieldErrors() {
return this.bindingResult.getFieldErrors();
}
@@ -178,7 +179,7 @@ public int getFieldErrorCount(String field) {
return this.bindingResult.getFieldErrorCount(field);
}
- public List getFieldErrors(String field) {
+ public List<FieldError> getFieldErrors(String field) {
return this.bindingResult.getFieldErrors(field);
}
@@ -190,7 +191,7 @@ public Object getFieldValue(String field) {
return this.bindingResult.getFieldValue(field);
}
- public Class getFieldType(String field) {
+ public Class<?> getFieldType(String field) {
return this.bindingResult.getFieldType(field);
}
@@ -206,6 +207,7 @@ public Object getRawFieldValue(String field) {
return this.bindingResult.getRawFieldValue(field);
}
+ @SuppressWarnings("rawtypes")
public PropertyEditor findEditor(String field, Class valueType) {
return this.bindingResult.findEditor(field, valueType);
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/BindingResult.java | @@ -94,7 +94,7 @@ public interface BindingResult extends Errors {
* is given but should be specified in any case for consistency checking)
* @return the registered editor, or <code>null</code> if none
*/
- PropertyEditor findEditor(String field, Class valueType);
+ PropertyEditor findEditor(String field, Class<?> valueType);
/**
* Return the underlying PropertyEditorRegistry. | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/BindingResultUtils.java | @@ -36,7 +36,7 @@ public abstract class BindingResultUtils {
* @return the BindingResult, or <code>null</code> if none found
* @throws IllegalStateException if the attribute found is not of type BindingResult
*/
- public static BindingResult getBindingResult(Map model, String name) {
+ public static BindingResult getBindingResult(Map<?, ?> model, String name) {
Assert.notNull(model, "Model map must not be null");
Assert.notNull(name, "Name must not be null");
Object attr = model.get(BindingResult.MODEL_KEY_PREFIX + name);
@@ -53,7 +53,7 @@ public static BindingResult getBindingResult(Map model, String name) {
* @return the BindingResult (never <code>null</code>)
* @throws IllegalStateException if no BindingResult found
*/
- public static BindingResult getRequiredBindingResult(Map model, String name) {
+ public static BindingResult getRequiredBindingResult(Map<?, ?> model, String name) {
BindingResult bindingResult = getBindingResult(model, name);
if (bindingResult == null) {
throw new IllegalStateException("No BindingResult attribute found for name '" + name + | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/DataBinder.java | @@ -509,18 +509,15 @@ public ConversionService getConversionService() {
return this.conversionService;
}
- @SuppressWarnings("unchecked")
- public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) {
+ public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);
}
- @SuppressWarnings("unchecked")
- public void registerCustomEditor(Class requiredType, String field, PropertyEditor propertyEditor) {
+ public void registerCustomEditor(Class<?> requiredType, String field, PropertyEditor propertyEditor) {
getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor);
}
- @SuppressWarnings("unchecked")
- public PropertyEditor findCustomEditor(Class requiredType, String propertyPath) {
+ public PropertyEditor findCustomEditor(Class<?> requiredType, String propertyPath) {
return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath);
}
@@ -700,8 +697,7 @@ public void validate() {
* @throws BindException if there were any errors in the bind operation
* @see BindingResult#getModel()
*/
- @SuppressWarnings("unchecked")
- public Map close() throws BindException {
+ public Map<?, ?> close() throws BindException {
if (getBindingResult().hasErrors()) {
throw new BindException(getBindingResult());
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java | @@ -75,6 +75,7 @@
* @author Juergen Hoeller
* @since 1.0.1
*/
+@SuppressWarnings("serial")
public class DefaultMessageCodesResolver implements MessageCodesResolver, Serializable {
/**
@@ -119,7 +120,7 @@ public String[] resolveMessageCodes(String errorCode, String objectName) {
* details on the generated codes.
* @return the list of codes
*/
- public String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) {
+ public String[] resolveMessageCodes(String errorCode, String objectName, String field, Class<?> fieldType) {
List<String> codeList = new ArrayList<String>();
List<String> fieldList = new ArrayList<String>();
buildFieldList(field, fieldList); | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/DirectFieldBindingResult.java | @@ -34,6 +34,7 @@
* @see DataBinder#initDirectFieldAccess()
* @see BeanPropertyBindingResult
*/
+@SuppressWarnings("serial")
public class DirectFieldBindingResult extends AbstractPropertyBindingResult {
private final Object target; | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/Errors.java | @@ -296,6 +296,6 @@ public interface Errors {
* @param field the field name
* @return the type of the field, or <code>null</code> if not determinable
*/
- Class getFieldType(String field);
+ Class<?> getFieldType(String field);
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/FieldError.java | @@ -31,6 +31,7 @@
* @since 10.03.2003
* @see DefaultMessageCodesResolver
*/
+@SuppressWarnings("serial")
public class FieldError extends ObjectError {
private final String field; | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/MapBindingResult.java | @@ -33,24 +33,25 @@
* @since 2.0
* @see java.util.Map
*/
+@SuppressWarnings("serial")
public class MapBindingResult extends AbstractBindingResult implements Serializable {
- private final Map target;
+ private final Map<?, ?> target;
/**
* Create a new MapBindingResult instance.
* @param target the target Map to bind onto
* @param objectName the name of the target object
*/
- public MapBindingResult(Map target, String objectName) {
+ public MapBindingResult(Map<?, ?> target, String objectName) {
super(objectName);
Assert.notNull(target, "Target Map must not be null");
this.target = target;
}
- public final Map getTargetMap() {
+ public final Map<?, ?> getTargetMap() {
return this.target;
}
| true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/MessageCodesResolver.java | @@ -50,6 +50,6 @@ public interface MessageCodesResolver {
* @param fieldType the field type (may be <code>null</code> if not determinable)
* @return the message codes to use
*/
- String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType);
+ String[] resolveMessageCodes(String errorCode, String objectName, String field, Class<?> fieldType);
} | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/ObjectError.java | @@ -31,6 +31,7 @@
* @see DefaultMessageCodesResolver
* @since 10.03.2003
*/
+@SuppressWarnings("serial")
public class ObjectError extends DefaultMessageSourceResolvable {
private final String objectName; | true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.java | @@ -62,6 +62,7 @@
public class LocalValidatorFactoryBean extends SpringValidatorAdapter
implements ValidatorFactory, ApplicationContextAware, InitializingBean {
+ @SuppressWarnings("rawtypes")
private Class providerClass;
private MessageInterpolator messageInterpolator;
@@ -85,6 +86,7 @@ public class LocalValidatorFactoryBean extends SpringValidatorAdapter
* @see javax.validation.Validation#byProvider(Class)
* @see javax.validation.Validation#byDefaultProvider()
*/
+ @SuppressWarnings("rawtypes")
public void setProviderClass(Class<? extends ValidationProvider> providerClass) {
this.providerClass = providerClass;
}
@@ -177,6 +179,7 @@ public void setApplicationContext(ApplicationContext applicationContext) {
@SuppressWarnings("unchecked")
public void afterPropertiesSet() {
+ @SuppressWarnings("rawtypes")
Configuration configuration = (this.providerClass != null ?
Validation.byProvider(this.providerClass).configure() :
Validation.byDefaultProvider().configure());
| true |
Other | spring-projects | spring-framework | f4e1cde33b077b1268cc5cae0c18c4b706653d25.json | Eliminate warnings in .validation package
Issue: SPR-8062 | org.springframework.context/src/main/java/org/springframework/validation/beanvalidation/package-info.java | @@ -3,8 +3,9 @@
* (such as Hibernate Validator 4.0) into a Spring ApplicationContext
* and in particular with Spring's data binding and validation APIs.
*
- * <p>The central class is {@link LocalValidatorFactoryBean} which
- * defines a shared ValidatorFactory/Validator setup for availability
+ * <p>The central class is {@link
+ * org.springframework.validation.beanvalidation.LocalValidatorFactoryBean}
+ * which defines a shared ValidatorFactory/Validator setup for availability
* to other Spring components.
*/
package org.springframework.validation.beanvalidation;
| true |
Other | spring-projects | spring-framework | 150838bfc13a136ef0baf943e378a8ebb5f3549f.json | Remove TODOs related to profile logging
Issue: SPR-8031, SPR-7508, SPR-8057 | org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2010 the original author or authors.
+ * Copyright 2002-2011 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.
@@ -123,7 +123,6 @@ protected void doRegisterBeanDefinitions(Element root) {
Assert.state(this.environment != null, "environment property must not be null");
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!this.environment.acceptsProfiles(specifiedProfiles)) {
- // TODO SPR-7508: log that this bean is being rejected on profile mismatch
return;
}
} | true |
Other | spring-projects | spring-framework | 150838bfc13a136ef0baf943e378a8ebb5f3549f.json | Remove TODOs related to profile logging
Issue: SPR-8031, SPR-7508, SPR-8057 | org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java | @@ -116,7 +116,6 @@ public void registerBean(Class<?> annotatedClass, String name, Class<? extends A
if (ProfileHelper.isProfileAnnotationPresent(metadata)) {
if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) {
- // TODO SPR-7508: log that this bean is being rejected on profile mismatch
return;
}
}
| true |
Other | spring-projects | spring-framework | 150838bfc13a136ef0baf943e378a8ebb5f3549f.json | Remove TODOs related to profile logging
Issue: SPR-8031, SPR-7508, SPR-8057 | org.springframework.context/src/main/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java | @@ -300,7 +300,6 @@ protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOE
if (!ProfileHelper.isProfileAnnotationPresent(metadata)) {
return true;
}
- // TODO SPR-7508: log that this bean is being rejected on profile mismatch
return this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata));
}
} | true |
Other | spring-projects | spring-framework | 150838bfc13a136ef0baf943e378a8ebb5f3549f.json | Remove TODOs related to profile logging
Issue: SPR-8031, SPR-7508, SPR-8057 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2010 the original author or authors.
+ * Copyright 2002-2011 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.
@@ -104,7 +104,6 @@ protected void processConfigurationClass(ConfigurationClass configClass) throws
AnnotationMetadata metadata = configClass.getMetadata();
if (this.environment != null && ProfileHelper.isProfileAnnotationPresent(metadata)) {
if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) {
- // TODO SPR-7508: log that this bean is being rejected on profile mismatch
return;
}
} | true |
Other | spring-projects | spring-framework | 150838bfc13a136ef0baf943e378a8ebb5f3549f.json | Remove TODOs related to profile logging
Issue: SPR-8031, SPR-7508, SPR-8057 | org.springframework.core/src/main/java/org/springframework/core/env/MutablePropertySources.java | @@ -160,7 +160,6 @@ protected void assertLegalRelativeAddition(String relativePropertySourceName, Pr
*/
protected void removeIfPresent(PropertySource<?> propertySource) {
if (this.propertySourceList.contains(propertySource)) {
- // TODO SPR-7508: add logging
this.propertySourceList.remove(propertySource);
}
} | true |
Other | spring-projects | spring-framework | a2a98efa13d35e30bd879f0ff92182900c805f5d.json | Remove references to 'bold' text in reference docs
<emphasis role="bold"> blocks do not render properly, probably due to
conflicting CSS used for syntax highlighting. For the moment, any
mentions of bold text (e.g. "see bold text in the snippet below") have
been removed to avoid confusion as reported in SPR-8520. SPR-8526 has
been created to address the underlying issue of getting bold to work
even with syntax highlighting.
Issue: SPR-8520, SPR-8526 | spring-framework-reference/src/oxm.xml | @@ -311,7 +311,7 @@ public class Application {
<para>
Marshallers could be configured more concisely using tags from the OXM namespace.
To make these tags available, the appropriate schema has to be referenced first in the preamble of the XML configuration file.
- The emboldened text in the below snippet references the OXM schema:
+ Note the 'oxm' related text below:
</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" | true |
Other | spring-projects | spring-framework | a2a98efa13d35e30bd879f0ff92182900c805f5d.json | Remove references to 'bold' text in reference docs
<emphasis role="bold"> blocks do not render properly, probably due to
conflicting CSS used for syntax highlighting. For the moment, any
mentions of bold text (e.g. "see bold text in the snippet below") have
been removed to avoid confusion as reported in SPR-8520. SPR-8526 has
been created to address the underlying issue of getting bold to work
even with syntax highlighting.
Issue: SPR-8520, SPR-8526 | spring-framework-reference/src/xsd-configuration.xml | @@ -99,7 +99,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
and suchlike.</para>
<para>To use the tags in the <literal>util</literal> schema, you need to have
the following preamble at the top of your Spring XML configuration file;
- the bold text in the snippet below references the correct schema so that
+ the text in the snippet below references the correct schema so that
the tags in the <literal>util</literal> namespace are available to you.</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -470,7 +470,7 @@ public class Client {
configuration issues, such as looking up a JNDI object and defining EJB references.</para>
<para>To use the tags in the <literal>jee</literal> schema, you need to have
the following preamble at the top of your Spring XML configuration file;
- the bold text in the following snippet references the correct schema so that
+ the text in the following snippet references the correct schema so that
the tags in the <literal>jee</literal> namespace are available to you.</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -628,7 +628,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
themselves.</para>
<para>In the interest of completeness, to use the tags in the <literal>lang</literal>
schema, you need to have the following preamble at the top of your Spring XML
- configuration file; the bold text in the following snippet references the
+ configuration file; the text in the following snippet references the
correct schema so that the tags in the <literal>lang</literal> namespace are
available to you.</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
@@ -653,7 +653,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
themselves.</para>
<para>In the interest of completeness, to use the tags in the <literal>jms</literal>
schema, you need to have the following preamble at the top of your Spring XML
- configuration file; the bold text in the following snippet references the
+ configuration file; the text in the following snippet references the
correct schema so that the tags in the <literal>jms</literal> namespace are
available to you.</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
@@ -685,7 +685,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
</tip>
<para>In the interest of completeness, to use the tags in the <literal>tx</literal>
schema, you need to have the following preamble at the top of your Spring XML
- configuration file; the bold text in the following snippet references the
+ configuration file; the text in the following snippet references the
correct schema so that the tags in the <literal>tx</literal> namespace are
available to you.</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
@@ -716,7 +716,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
comprehensively covered in the chapter entitled <xref linkend="aop"/>.</para>
<para>In the interest of completeness, to use the tags in the <literal>aop</literal>
schema, you need to have the following preamble at the top of your Spring XML
- configuration file; the bold text in the following snippet references the
+ configuration file; the text in the following snippet references the
correct schema so that the tags in the <literal>aop</literal> namespace are
available to you.</para>
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?> | true |
Other | spring-projects | spring-framework | 5aa24af1269bf0ac9691afc63da6f6051543ad6a.json | Implement SessionFactoryImplementor in SF proxies
SessionFactoryBuilderSupport implementations create DisposableBean
proxies for SessionFactory objects created using #buildSessionFactory.
Prior to this change, these proxies create problems when working agaist
SessionFactoryUtils.getDataSource(SessionFactory), because this method
expects the given SessionFactory to implement Hibernate's
SessionFactoryImplementor interface (which the stock SessionFactoryImpl
does).
With this change, the DisposableBean proxies created by SFBuilders
now also implement SessionFactoryImplementor to satisfy this and
probably other such cases.
Issue: SPR-8469 | org.springframework.integration-tests/src/test/java/org/springframework/orm/hibernate3/HibernateSessionFactoryConfigurationTests.java | @@ -33,6 +33,7 @@
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
+import org.hibernate.engine.SessionFactoryImplementor;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
@@ -131,10 +132,11 @@ public void usingSessionFactoryBuilder_withLateCustomConfigurationClass() throws
}
@Test
- public void builtSessionFactoryIsDisposableBeanProxy() {
+ public void builtSessionFactoryIsProxyImplementingDisposableBeanAndSessionFactoryImplementor() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AnnotationSessionFactoryConfig.class);
SessionFactory sessionFactory = ctx.getBean(SessionFactory.class);
assertThat(sessionFactory, instanceOf(DisposableBean.class));
+ assertThat(sessionFactory, instanceOf(SessionFactoryImplementor.class));
assertThat(sessionFactory.toString(), startsWith("DisposableBean proxy for SessionFactory"));
ctx.close();
assertTrue("SessionFactory was not closed as expected", sessionFactory.isClosed()); | true |
Other | spring-projects | spring-framework | 5aa24af1269bf0ac9691afc63da6f6051543ad6a.json | Implement SessionFactoryImplementor in SF proxies
SessionFactoryBuilderSupport implementations create DisposableBean
proxies for SessionFactory objects created using #buildSessionFactory.
Prior to this change, these proxies create problems when working agaist
SessionFactoryUtils.getDataSource(SessionFactory), because this method
expects the given SessionFactory to implement Hibernate's
SessionFactoryImplementor interface (which the stock SessionFactoryImpl
does).
With this change, the DisposableBean proxies created by SFBuilders
now also implement SessionFactoryImplementor to satisfy this and
probably other such cases.
Issue: SPR-8469 | org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryBuilderSupport.java | @@ -232,8 +232,9 @@ public SessionFactoryBuilderSupport(DataSource dataSource) {
/**
* Build the underlying Hibernate SessionFactory.
- * @return the raw SessionFactory (potentially to be wrapped with a
- * transaction-aware proxy before it is exposed to the application)
+ * @return the {@code SessionFactory}, potentially wrapped as a
+ * {@code DisposableBean} and/or transaction-aware proxy before it is exposed to the
+ * application.
* @throws Exception in case of initialization failure
*/
public SessionFactory buildSessionFactory() throws Exception {
@@ -244,8 +245,9 @@ public SessionFactory buildSessionFactory() throws Exception {
/**
* Populate the underlying {@code Configuration} instance with the various
- * properties of this builder. Customization may be performed through
- * {@code pre*} and {@code post*} methods.
+ * properties of this builder, then return the raw session factory resulting from
+ * calling {@link Configuration#buildSessionFactory()}. Customization may be performed
+ * through {@code pre*} and {@code post*} methods.
* @see #preBuildSessionFactory()
* @see #postProcessMappings()
* @see #postBuildSessionFactory()
@@ -565,15 +567,17 @@ protected void postBuildSessionFactory() {
* <p>Subclasses may override this to implement transaction awareness through
* a {@code SessionFactory} proxy for example, or even to avoid creation of the
* {@code DisposableBean} proxy altogether.
- * @param rawSf the raw {@code SessionFactory} as built by {@link #buildSessionFactory()}
- * @return the {@code SessionFactory} reference to expose
+ * @param rawSf the raw {@code SessionFactory} as built by {@link #doBuildSessionFactory()}
+ * @return a proxied {@code SessionFactory} if wrapping was necessary, otherwise the
+ * original given 'raw' {@code SessionFactory} object.
* @see #buildSessionFactory()
*/
protected SessionFactory wrapSessionFactoryIfNecessary(final SessionFactory rawSf) {
return (SessionFactory) Proxy.newProxyInstance(
this.beanClassLoader,
new Class<?>[] {
SessionFactory.class,
+ SessionFactoryImplementor.class,
DisposableBean.class
},
new InvocationHandler() { | true |
Other | spring-projects | spring-framework | 807d612978f9d01e446542320c19db68da14b8e1.json | 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 | org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java | @@ -21,6 +21,9 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.WildcardType;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
@@ -68,6 +71,7 @@
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.TypedStringValue;
+import org.springframework.core.GenericTypeResolver;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
@@ -651,7 +655,9 @@ protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd,
}
/**
- * This implementation checks the FactoryBean's <code>getObjectType</code> method
+ * This implementation attempts to query the FactoryBean's generic parameter metadata
+ * if present to determin the object type. If not present, i.e. the FactoryBean is
+ * declared as a raw type, checks the FactoryBean's <code>getObjectType</code> method
* on a plain instance of the FactoryBean, without bean properties applied yet.
* If this doesn't return a type yet, a full creation of the FactoryBean is
* used as fallback (through delegation to the superclass's implementation).
@@ -660,14 +666,34 @@ protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd,
* it will be fully created to check the type of its exposed object.
*/
@Override
- protected Class getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
- FactoryBean fb = (mbd.isSingleton() ?
+ protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
+ Class<?> objectType = null;
+ String factoryBeanName = mbd.getFactoryBeanName();
+ String factoryMethodName = mbd.getFactoryMethodName();
+ if (factoryBeanName != null && factoryMethodName != null) {
+ // Try to obtain the FactoryBean's object type without instantiating it at all.
+ BeanDefinition fbDef = getBeanDefinition(factoryBeanName);
+ if (fbDef instanceof AbstractBeanDefinition) {
+ Class<?> fbClass = ((AbstractBeanDefinition)fbDef).getBeanClass();
+ if (ClassUtils.isCglibProxyClass(fbClass)) {
+ // CGLIB subclass methods hide generic parameters. look at the superclass.
+ fbClass = fbClass.getSuperclass();
+ }
+ Method m = ReflectionUtils.findMethod(fbClass, factoryMethodName);
+ objectType = GenericTypeResolver.resolveReturnTypeArgument(m, FactoryBean.class);
+ if (objectType != null) {
+ return objectType;
+ }
+ }
+ }
+
+ FactoryBean<?> fb = (mbd.isSingleton() ?
getSingletonFactoryBeanForTypeCheck(beanName, mbd) :
getNonSingletonFactoryBeanForTypeCheck(beanName, mbd));
if (fb != null) {
// Try to obtain the FactoryBean's object type from this early stage of the instance.
- Class objectType = getTypeForFactoryBean(fb);
+ objectType = getTypeForFactoryBean(fb);
if (objectType != null) {
return objectType;
} | true |
Other | spring-projects | spring-framework | 807d612978f9d01e446542320c19db68da14b8e1.json | 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 | org.springframework.context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndAutowiringTests.java | @@ -0,0 +1,218 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import org.junit.Test;
+import org.springframework.beans.factory.BeanCreationException;
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.util.Assert;
+
+/**
+ * Tests cornering bug SPR-8514.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+public class ConfigurationWithFactoryBeanAndAutowiringTests {
+
+ @Test
+ public void withConcreteFactoryBeanImplementationAsReturnType() {
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext();
+ ctx.register(AppConfig.class);
+ ctx.register(ConcreteFactoryBeanImplementationConfig.class);
+ ctx.refresh();
+ }
+
+ @Test
+ public void withParameterizedFactoryBeanImplementationAsReturnType() {
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext();
+ ctx.register(AppConfig.class);
+ ctx.register(ParameterizedFactoryBeanImplementationConfig.class);
+ ctx.refresh();
+ }
+
+ @Test
+ public void withParameterizedFactoryBeanInterfaceAsReturnType() {
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext();
+ ctx.register(AppConfig.class);
+ ctx.register(ParameterizedFactoryBeanInterfaceConfig.class);
+ ctx.refresh();
+ }
+
+ @Test
+ public void withNonPublicParameterizedFactoryBeanInterfaceAsReturnType() {
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext();
+ ctx.register(AppConfig.class);
+ ctx.register(NonPublicParameterizedFactoryBeanInterfaceConfig.class);
+ ctx.refresh();
+ }
+
+ @Test(expected=BeanCreationException.class)
+ public void withRawFactoryBeanInterfaceAsReturnType() {
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext();
+ ctx.register(AppConfig.class);
+ ctx.register(RawFactoryBeanInterfaceConfig.class);
+ ctx.refresh();
+ }
+
+ @Test(expected=BeanCreationException.class)
+ public void withWildcardParameterizedFactoryBeanInterfaceAsReturnType() {
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext();
+ ctx.register(AppConfig.class);
+ ctx.register(WildcardParameterizedFactoryBeanInterfaceConfig.class);
+ ctx.refresh();
+ }
+
+}
+
+
+class DummyBean {
+}
+
+
+class MyFactoryBean implements FactoryBean<String> {
+ public String getObject() throws Exception {
+ return "foo";
+ }
+ public Class<String> getObjectType() {
+ return String.class;
+ }
+ public boolean isSingleton() {
+ return true;
+ }
+}
+
+
+class MyParameterizedFactoryBean<T> implements FactoryBean<T> {
+
+ private final T obj;
+
+ public MyParameterizedFactoryBean(T obj) {
+ this.obj = obj;
+ }
+
+ public T getObject() throws Exception {
+ return obj;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Class<T> getObjectType() {
+ return (Class<T>)obj.getClass();
+ }
+
+ public boolean isSingleton() {
+ return true;
+ }
+}
+
+
+@Configuration
+class AppConfig {
+ @Bean
+ public DummyBean dummyBean() {
+ return new DummyBean();
+ }
+}
+
+
+@Configuration
+class ConcreteFactoryBeanImplementationConfig {
+ @Autowired
+ private DummyBean dummyBean;
+
+ @Bean
+ public MyFactoryBean factoryBean() {
+ Assert.notNull(dummyBean, "DummyBean was not injected.");
+ return new MyFactoryBean();
+ }
+}
+
+
+@Configuration
+class ParameterizedFactoryBeanImplementationConfig {
+ @Autowired
+ private DummyBean dummyBean;
+
+ @Bean
+ public MyParameterizedFactoryBean<String> factoryBean() {
+ Assert.notNull(dummyBean, "DummyBean was not injected.");
+ return new MyParameterizedFactoryBean<String>("whatev");
+ }
+}
+
+
+@Configuration
+class ParameterizedFactoryBeanInterfaceConfig {
+ @Autowired
+ private DummyBean dummyBean;
+
+ @Bean
+ public FactoryBean<String> factoryBean() {
+ Assert.notNull(dummyBean, "DummyBean was not injected.");
+ return new MyFactoryBean();
+ }
+}
+
+
+@Configuration
+class NonPublicParameterizedFactoryBeanInterfaceConfig {
+ @Autowired
+ private DummyBean dummyBean;
+
+ @Bean
+ FactoryBean<String> factoryBean() {
+ Assert.notNull(dummyBean, "DummyBean was not injected.");
+ return new MyFactoryBean();
+ }
+}
+
+
+@Configuration
+class RawFactoryBeanInterfaceConfig {
+ @Autowired
+ private DummyBean dummyBean;
+
+ @Bean
+ @SuppressWarnings("rawtypes")
+ public FactoryBean factoryBean() {
+ Assert.notNull(dummyBean, "DummyBean was not injected.");
+ return new MyFactoryBean();
+ }
+}
+
+
+@Configuration
+class WildcardParameterizedFactoryBeanInterfaceConfig {
+ @Autowired
+ private DummyBean dummyBean;
+
+ @Bean
+ public FactoryBean<?> factoryBean() {
+ Assert.notNull(dummyBean, "DummyBean was not injected.");
+ return new MyFactoryBean();
+ }
+} | true |
Other | spring-projects | spring-framework | ce0a0ff3d4352b3040e7bbc7fe14313a40ac9491.json | Move JNDI_PROPERTY_SOURCE_ENABLED_FLAG constant
Move JNDI_PROPERTY_SOURCE_ENABLED_FLAG from JndiPropertySource to
StandardServletEnvironment, as this is the only context in which the
constant makes sense. | org.springframework.context/src/main/java/org/springframework/jndi/JndiPropertySource.java | @@ -42,12 +42,6 @@ public class JndiPropertySource extends PropertySource<Context> {
/** JNDI context property source name: {@value} */
public static final String JNDI_PROPERTY_SOURCE_NAME = "jndiPropertySource";
- /**
- * Name of property used to determine if a {@link JndiPropertySource}
- * should be registered by default: {@value}
- */
- public static final String JNDI_PROPERTY_SOURCE_ENABLED_FLAG = "jndiPropertySourceEnabled";
-
/**
* Create a new {@code JndiPropertySource} with the default name
* {@value #JNDI_PROPERTY_SOURCE_NAME} and create a new {@link InitialContext} | true |
Other | spring-projects | spring-framework | ce0a0ff3d4352b3040e7bbc7fe14313a40ac9491.json | Move JNDI_PROPERTY_SOURCE_ENABLED_FLAG constant
Move JNDI_PROPERTY_SOURCE_ENABLED_FLAG from JndiPropertySource to
StandardServletEnvironment, as this is the only context in which the
constant makes sense. | org.springframework.web/src/main/java/org/springframework/web/context/support/StandardServletEnvironment.java | @@ -55,6 +55,13 @@ public class StandardServletEnvironment extends StandardEnvironment {
/** Servlet config init parameters property source name: {@value} */
public static final String SERVLET_CONFIG_PROPERTY_SOURCE_NAME = "servletConfigInitParams";
+ /**
+ * Name of property used to determine if a {@link JndiPropertySource}
+ * should be registered by default: {@value}
+ */
+ public static final String JNDI_PROPERTY_SOURCE_ENABLED_FLAG = "jndiPropertySourceEnabled";
+
+
/**
* Customize the set of property sources with those contributed by superclasses as
* well as those appropriate for standard servlet-based environments:
@@ -90,7 +97,7 @@ protected void customizePropertySources(MutablePropertySources propertySources)
propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME));
super.customizePropertySources(propertySources);
- if (this.getProperty(JndiPropertySource.JNDI_PROPERTY_SOURCE_ENABLED_FLAG, boolean.class, false)) {
+ if (this.getProperty(JNDI_PROPERTY_SOURCE_ENABLED_FLAG, boolean.class, false)) {
propertySources.addAfter(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, new JndiPropertySource());
}
} | true |
Other | spring-projects | spring-framework | ce0a0ff3d4352b3040e7bbc7fe14313a40ac9491.json | Move JNDI_PROPERTY_SOURCE_ENABLED_FLAG constant
Move JNDI_PROPERTY_SOURCE_ENABLED_FLAG from JndiPropertySource to
StandardServletEnvironment, as this is the only context in which the
constant makes sense. | org.springframework.web/src/test/java/org/springframework/web/context/support/StandardServletEnvironmentTests.java | @@ -19,6 +19,7 @@
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
+import static org.springframework.web.context.support.StandardServletEnvironment.JNDI_PROPERTY_SOURCE_ENABLED_FLAG;
import org.junit.Test;
import org.springframework.core.env.ConfigurableEnvironment;
@@ -48,7 +49,7 @@ public void propertySourceOrder() {
@Test
public void propertySourceOrder_jndiPropertySourceEnabled() {
- System.setProperty(JndiPropertySource.JNDI_PROPERTY_SOURCE_ENABLED_FLAG, "true");
+ System.setProperty(JNDI_PROPERTY_SOURCE_ENABLED_FLAG, "true");
ConfigurableEnvironment env = new StandardServletEnvironment();
MutablePropertySources sources = env.getPropertySources();
@@ -59,12 +60,12 @@ public void propertySourceOrder_jndiPropertySourceEnabled() {
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4));
assertThat(sources.size(), is(5));
- System.clearProperty(JndiPropertySource.JNDI_PROPERTY_SOURCE_ENABLED_FLAG);
+ System.clearProperty(JNDI_PROPERTY_SOURCE_ENABLED_FLAG);
}
@Test
public void propertySourceOrder_jndiPropertySourceEnabledIsFalse() {
- System.setProperty(JndiPropertySource.JNDI_PROPERTY_SOURCE_ENABLED_FLAG, "false");
+ System.setProperty(JNDI_PROPERTY_SOURCE_ENABLED_FLAG, "false");
ConfigurableEnvironment env = new StandardServletEnvironment();
MutablePropertySources sources = env.getPropertySources();
@@ -75,6 +76,6 @@ public void propertySourceOrder_jndiPropertySourceEnabledIsFalse() {
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(3));
assertThat(sources.size(), is(4));
- System.clearProperty(JndiPropertySource.JNDI_PROPERTY_SOURCE_ENABLED_FLAG);
+ System.clearProperty(JNDI_PROPERTY_SOURCE_ENABLED_FLAG);
}
} | true |
Other | spring-projects | spring-framework | 32ebf18429a179e6bf416db42ae2d474802369ea.json | SPR-5937: add param map to freemarker url macro | org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java | @@ -46,21 +46,18 @@
import org.springframework.web.util.WebUtils;
/**
- * Context holder for request-specific state, like current web application
- * context, current locale, current theme, and potential binding errors.
- * Provides easy access to localized messages and Errors instances.
- *
- * <p>Suitable for exposition to views, and usage within JSP's "useBean" tag,
- * JSP scriptlets, JSTL EL, Velocity templates, etc. Necessary for views
- * that do not have access to the servlet request, like Velocity templates.
- *
- * <p>Can be instantiated manually, or automatically exposed to views as
- * model attribute via AbstractView's "requestContextAttribute" property.
- *
- * <p>Will also work outside of DispatcherServlet requests, accessing the root
- * WebApplicationContext and using an appropriate fallback for the locale
- * (the HttpServletRequest's primary locale).
- *
+ * Context holder for request-specific state, like current web application context, current locale, current theme, and
+ * potential binding errors. Provides easy access to localized messages and Errors instances.
+ *
+ * <p>Suitable for exposition to views, and usage within JSP's "useBean" tag, JSP scriptlets, JSTL EL, Velocity
+ * templates, etc. Necessary for views that do not have access to the servlet request, like Velocity templates.
+ *
+ * <p>Can be instantiated manually, or automatically exposed to views as model attribute via AbstractView's
+ * "requestContextAttribute" property.
+ *
+ * <p>Will also work outside of DispatcherServlet requests, accessing the root WebApplicationContext and using an
+ * appropriate fallback for the locale (the HttpServletRequest's primary locale).
+ *
* @author Juergen Hoeller
* @since 03.03.2003
* @see org.springframework.web.servlet.DispatcherServlet
@@ -71,24 +68,20 @@
public class RequestContext {
/**
- * Default theme name used if the RequestContext cannot find a ThemeResolver.
- * Only applies to non-DispatcherServlet requests.
- * <p>Same as AbstractThemeResolver's default, but not linked in here to
- * avoid package interdependencies.
+ * Default theme name used if the RequestContext cannot find a ThemeResolver. Only applies to non-DispatcherServlet
+ * requests. <p>Same as AbstractThemeResolver's default, but not linked in here to avoid package interdependencies.
* @see org.springframework.web.servlet.theme.AbstractThemeResolver#ORIGINAL_DEFAULT_THEME_NAME
*/
public static final String DEFAULT_THEME_NAME = "theme";
/**
- * Request attribute to hold the current web application context for RequestContext usage.
- * By default, the DispatcherServlet's context (or the root context as fallback) is exposed.
+ * Request attribute to hold the current web application context for RequestContext usage. By default, the
+ * DispatcherServlet's context (or the root context as fallback) is exposed.
*/
public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = RequestContext.class.getName() + ".CONTEXT";
-
- protected static final boolean jstlPresent = ClassUtils.isPresent(
- "javax.servlet.jsp.jstl.core.Config", RequestContext.class.getClassLoader());
-
+ protected static final boolean jstlPresent = ClassUtils.isPresent("javax.servlet.jsp.jstl.core.Config",
+ RequestContext.class.getClassLoader());
private HttpServletRequest request;
@@ -108,15 +101,11 @@ public class RequestContext {
private Map<String, Errors> errorsMap;
-
/**
- * Create a new RequestContext for the given request,
- * using the request attributes for Errors retrieval.
- * <p>This only works with InternalResourceViews, as Errors instances
- * are part of the model and not normally exposed as request attributes.
- * It will typically be used within JSPs or custom tags.
- * <p><b>Will only work within a DispatcherServlet request.</b> Pass in a
- * ServletContext to be able to fallback to the root WebApplicationContext.
+ * Create a new RequestContext for the given request, using the request attributes for Errors retrieval. <p>This
+ * only works with InternalResourceViews, as Errors instances are part of the model and not normally exposed as
+ * request attributes. It will typically be used within JSPs or custom tags. <p><b>Will only work within a
+ * DispatcherServlet request.</b> Pass in a ServletContext to be able to fallback to the root WebApplicationContext.
* @param request current HTTP request
* @see org.springframework.web.servlet.DispatcherServlet
* @see #RequestContext(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext)
@@ -126,16 +115,13 @@ public RequestContext(HttpServletRequest request) {
}
/**
- * Create a new RequestContext for the given request,
- * using the request attributes for Errors retrieval.
- * <p>This only works with InternalResourceViews, as Errors instances
- * are part of the model and not normally exposed as request attributes.
- * It will typically be used within JSPs or custom tags.
- * <p>If a ServletContext is specified, the RequestContext will also
- * work with the root WebApplicationContext (outside a DispatcherServlet).
+ * Create a new RequestContext for the given request, using the request attributes for Errors retrieval. <p>This
+ * only works with InternalResourceViews, as Errors instances are part of the model and not normally exposed as
+ * request attributes. It will typically be used within JSPs or custom tags. <p>If a ServletContext is specified,
+ * the RequestContext will also work with the root WebApplicationContext (outside a DispatcherServlet).
* @param request current HTTP request
- * @param servletContext the servlet context of the web application
- * (can be <code>null</code>; necessary for fallback to root WebApplicationContext)
+ * @param servletContext the servlet context of the web application (can be <code>null</code>; necessary for
+ * fallback to root WebApplicationContext)
* @see org.springframework.web.context.WebApplicationContext
* @see org.springframework.web.servlet.DispatcherServlet
*/
@@ -144,15 +130,13 @@ public RequestContext(HttpServletRequest request, ServletContext servletContext)
}
/**
- * Create a new RequestContext for the given request,
- * using the given model attributes for Errors retrieval.
- * <p>This works with all View implementations.
- * It will typically be used by View implementations.
- * <p><b>Will only work within a DispatcherServlet request.</b> Pass in a
- * ServletContext to be able to fallback to the root WebApplicationContext.
+ * Create a new RequestContext for the given request, using the given model attributes for Errors retrieval. <p>This
+ * works with all View implementations. It will typically be used by View implementations. <p><b>Will only work
+ * within a DispatcherServlet request.</b> Pass in a ServletContext to be able to fallback to the root
+ * WebApplicationContext.
* @param request current HTTP request
- * @param model the model attributes for the current view
- * (can be <code>null</code>, using the request attributes for Errors retrieval)
+ * @param model the model attributes for the current view (can be <code>null</code>, using the request attributes
+ * for Errors retrieval)
* @see org.springframework.web.servlet.DispatcherServlet
* @see #RequestContext(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext, Map)
*/
@@ -161,23 +145,20 @@ public RequestContext(HttpServletRequest request, Map<String, Object> model) {
}
/**
- * Create a new RequestContext for the given request,
- * using the given model attributes for Errors retrieval.
- * <p>This works with all View implementations.
- * It will typically be used by View implementations.
- * <p>If a ServletContext is specified, the RequestContext will also
- * work with a root WebApplicationContext (outside a DispatcherServlet).
+ * Create a new RequestContext for the given request, using the given model attributes for Errors retrieval. <p>This
+ * works with all View implementations. It will typically be used by View implementations. <p>If a ServletContext is
+ * specified, the RequestContext will also work with a root WebApplicationContext (outside a DispatcherServlet).
* @param request current HTTP request
* @param response current HTTP response
- * @param servletContext the servlet context of the web application
- * (can be <code>null</code>; necessary for fallback to root WebApplicationContext)
- * @param model the model attributes for the current view
- * (can be <code>null</code>, using the request attributes for Errors retrieval)
+ * @param servletContext the servlet context of the web application (can be <code>null</code>; necessary for
+ * fallback to root WebApplicationContext)
+ * @param model the model attributes for the current view (can be <code>null</code>, using the request attributes
+ * for Errors retrieval)
* @see org.springframework.web.context.WebApplicationContext
* @see org.springframework.web.servlet.DispatcherServlet
*/
- public RequestContext(HttpServletRequest request, HttpServletResponse response,
- ServletContext servletContext, Map<String, Object> model) {
+ public RequestContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext,
+ Map<String, Object> model) {
initContext(request, response, servletContext, model);
}
@@ -188,34 +169,30 @@ public RequestContext(HttpServletRequest request, HttpServletResponse response,
protected RequestContext() {
}
-
/**
- * Initialize this context with the given request,
- * using the given model attributes for Errors retrieval.
- * <p>Delegates to <code>getFallbackLocale</code> and <code>getFallbackTheme</code>
- * for determining the fallback locale and theme, respectively, if no LocaleResolver
- * and/or ThemeResolver can be found in the request.
+ * Initialize this context with the given request, using the given model attributes for Errors retrieval.
+ * <p>Delegates to <code>getFallbackLocale</code> and <code>getFallbackTheme</code> for determining the fallback
+ * locale and theme, respectively, if no LocaleResolver and/or ThemeResolver can be found in the request.
* @param request current HTTP request
- * @param servletContext the servlet context of the web application
- * (can be <code>null</code>; necessary for fallback to root WebApplicationContext)
- * @param model the model attributes for the current view
- * (can be <code>null</code>, using the request attributes for Errors retrieval)
+ * @param servletContext the servlet context of the web application (can be <code>null</code>; necessary for
+ * fallback to root WebApplicationContext)
+ * @param model the model attributes for the current view (can be <code>null</code>, using the request attributes
+ * for Errors retrieval)
* @see #getFallbackLocale
* @see #getFallbackTheme
* @see org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_ATTRIBUTE
* @see org.springframework.web.servlet.DispatcherServlet#THEME_RESOLVER_ATTRIBUTE
*/
- protected void initContext(HttpServletRequest request, HttpServletResponse response,
- ServletContext servletContext, Map<String, Object> model) {
+ protected void initContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext,
+ Map<String, Object> model) {
this.request = request;
this.response = response;
this.model = model;
// Fetch WebApplicationContext, either from DispatcherServlet or the root context.
// ServletContext needs to be specified to be able to fall back to the root context!
- this.webApplicationContext =
- (WebApplicationContext) request.getAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE);
+ this.webApplicationContext = (WebApplicationContext) request.getAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (this.webApplicationContext == null) {
this.webApplicationContext = RequestContextUtils.getWebApplicationContext(request, servletContext);
}
@@ -225,8 +202,7 @@ protected void initContext(HttpServletRequest request, HttpServletResponse respo
if (localeResolver != null) {
// Try LocaleResolver (we're within a DispatcherServlet request).
this.locale = localeResolver.resolveLocale(request);
- }
- else {
+ } else {
// No LocaleResolver available -> try fallback.
this.locale = getFallbackLocale();
}
@@ -239,10 +215,8 @@ protected void initContext(HttpServletRequest request, HttpServletResponse respo
}
/**
- * Determine the fallback locale for this context.
- * <p>The default implementation checks for a JSTL locale attribute
- * in request, session or application scope; if not found,
- * returns the <code>HttpServletRequest.getLocale()</code>.
+ * Determine the fallback locale for this context. <p>The default implementation checks for a JSTL locale attribute
+ * in request, session or application scope; if not found, returns the <code>HttpServletRequest.getLocale()</code>.
* @return the fallback locale (never <code>null</code>)
* @see javax.servlet.http.HttpServletRequest#getLocale()
*/
@@ -257,8 +231,8 @@ protected Locale getFallbackLocale() {
}
/**
- * Determine the fallback theme for this context.
- * <p>The default implementation returns the default theme (with name "theme").
+ * Determine the fallback theme for this context. <p>The default implementation returns the default theme (with name
+ * "theme").
* @return the fallback theme (never <code>null</code>)
*/
protected Theme getFallbackTheme() {
@@ -273,18 +247,15 @@ protected Theme getFallbackTheme() {
return theme;
}
-
/**
- * Return the underlying HttpServletRequest.
- * Only intended for cooperating classes in this package.
+ * Return the underlying HttpServletRequest. Only intended for cooperating classes in this package.
*/
protected final HttpServletRequest getRequest() {
return this.request;
}
/**
- * Return the underlying ServletContext.
- * Only intended for cooperating classes in this package.
+ * Return the underlying ServletContext. Only intended for cooperating classes in this package.
*/
protected final ServletContext getServletContext() {
return this.webApplicationContext.getServletContext();
@@ -320,8 +291,8 @@ public final Locale getLocale() {
}
/**
- * Return the current theme (never <code>null</code>).
- * <p>Resolved lazily for more efficiency when theme support is not being used.
+ * Return the current theme (never <code>null</code>). <p>Resolved lazily for more efficiency when theme support is
+ * not being used.
*/
public final Theme getTheme() {
if (this.theme == null) {
@@ -335,59 +306,51 @@ public final Theme getTheme() {
return this.theme;
}
-
/**
- * (De)activate default HTML escaping for messages and errors, for the scope
- * of this RequestContext. The default is the application-wide setting
- * (the "defaultHtmlEscape" context-param in web.xml).
+ * (De)activate default HTML escaping for messages and errors, for the scope of this RequestContext. The default is
+ * the application-wide setting (the "defaultHtmlEscape" context-param in web.xml).
* @see org.springframework.web.util.WebUtils#isDefaultHtmlEscape
*/
public void setDefaultHtmlEscape(boolean defaultHtmlEscape) {
this.defaultHtmlEscape = defaultHtmlEscape;
}
/**
- * Is default HTML escaping active?
- * Falls back to <code>false</code> in case of no explicit default given.
+ * Is default HTML escaping active? Falls back to <code>false</code> in case of no explicit default given.
*/
public boolean isDefaultHtmlEscape() {
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape.booleanValue());
}
/**
- * Return the default HTML escape setting, differentiating
- * between no default specified and an explicit value.
+ * Return the default HTML escape setting, differentiating between no default specified and an explicit value.
* @return whether default HTML escaping is enabled (null = no explicit default)
*/
public Boolean getDefaultHtmlEscape() {
return this.defaultHtmlEscape;
}
/**
- * Set the UrlPathHelper to use for context path and request URI decoding.
- * Can be used to pass a shared UrlPathHelper instance in.
- * <p>A default UrlPathHelper is always available.
+ * Set the UrlPathHelper to use for context path and request URI decoding. Can be used to pass a shared
+ * UrlPathHelper instance in. <p>A default UrlPathHelper is always available.
*/
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");
this.urlPathHelper = urlPathHelper;
}
/**
- * Return the UrlPathHelper used for context path and request URI decoding.
- * Can be used to configure the current UrlPathHelper.
- * <p>A default UrlPathHelper is always available.
+ * Return the UrlPathHelper used for context path and request URI decoding. Can be used to configure the current
+ * UrlPathHelper. <p>A default UrlPathHelper is always available.
*/
public UrlPathHelper getUrlPathHelper() {
return this.urlPathHelper;
}
-
/**
- * Return the context path of the original request,
- * that is, the path that indicates the current web application.
- * This is useful for building links to other resources within the application.
- * <p>Delegates to the UrlPathHelper for decoding.
+ * Return the context path of the original request, that is, the path that indicates the current web application.
+ * This is useful for building links to other resources within the application. <p>Delegates to the UrlPathHelper
+ * for decoding.
* @see javax.servlet.http.HttpServletRequest#getContextPath
* @see #getUrlPathHelper
*/
@@ -398,8 +361,7 @@ public String getContextPath() {
/**
* Return a context-aware URl for the given relative URL.
* @param relativeUrl the relative URL part
- * @return a URL that points back to the server with an absolute path
- * (also URL-encoded accordingly)
+ * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly)
*/
public String getContextUrl(String relativeUrl) {
String url = getContextPath() + relativeUrl;
@@ -410,13 +372,15 @@ public String getContextUrl(String relativeUrl) {
}
/**
- * Return a context-aware URl for the given relative URL with placeholders (named keys with braces <code>{}</code>).
+ * Return a context-aware URl for the given relative URL with placeholders (named keys with braces <code>{}</code>).
+ * For example, send in a relative URL <code>foo/{bar}?spam={spam}</code> and a parameter map
+ * <code>{bar=baz,spam=nuts}</code> and the result will be <code>[contextpath]/foo/baz?spam=nuts</code>.
+ *
* @param relativeUrl the relative URL part
* @param a map of parameters to insert as placeholders in the url
- * @return a URL that points back to the server with an absolute path
- * (also URL-encoded accordingly)
+ * @return a URL that points back to the server with an absolute path (also URL-encoded accordingly)
*/
- public String getContextUrl(String relativeUrl, Map<String,?> params) {
+ public String getContextUrl(String relativeUrl, Map<String, ?> params) {
String url = getContextPath() + relativeUrl;
UriTemplate template = new UriTemplate(url);
url = template.expand(params).toASCIIString();
@@ -427,13 +391,11 @@ public String getContextUrl(String relativeUrl, Map<String,?> params) {
}
/**
- * Return the request URI of the original request, that is, the invoked URL
- * without parameters. This is particularly useful as HTML form action target,
- * possibly in combination with the original query string.
- * <p><b>Note this implementation will correctly resolve to the URI of any
- * originating root request in the presence of a forwarded request. However, this
- * can only work when the Servlet 2.4 'forward' request attributes are present.
- * <p>Delegates to the UrlPathHelper for decoding.
+ * Return the request URI of the original request, that is, the invoked URL without parameters. This is particularly
+ * useful as HTML form action target, possibly in combination with the original query string. <p><b>Note this
+ * implementation will correctly resolve to the URI of any originating root request in the presence of a forwarded
+ * request. However, this can only work when the Servlet 2.4 'forward' request attributes are present. <p>Delegates
+ * to the UrlPathHelper for decoding.
* @see #getQueryString
* @see org.springframework.web.util.UrlPathHelper#getOriginatingRequestUri
* @see #getUrlPathHelper
@@ -443,12 +405,10 @@ public String getRequestUri() {
}
/**
- * Return the query string of the current request, that is, the part after
- * the request path. This is particularly useful for building an HTML form
- * action target in combination with the original request URI.
- * <p><b>Note this implementation will correctly resolve to the query string of any
- * originating root request in the presence of a forwarded request. However, this
- * can only work when the Servlet 2.4 'forward' request attributes are present.
+ * Return the query string of the current request, that is, the part after the request path. This is particularly
+ * useful for building an HTML form action target in combination with the original request URI. <p><b>Note this
+ * implementation will correctly resolve to the query string of any originating root request in the presence of a
+ * forwarded request. However, this can only work when the Servlet 2.4 'forward' request attributes are present.
* <p>Delegates to the UrlPathHelper for decoding.
* @see #getRequestUri
* @see org.springframework.web.util.UrlPathHelper#getOriginatingQueryString
@@ -458,7 +418,6 @@ public String getQueryString() {
return this.urlPathHelper.getOriginatingQueryString(this.request);
}
-
/**
* Retrieve the message for the given code, using the "defaultHtmlEscape" setting.
* @param code code of the message
@@ -550,8 +509,7 @@ public String getMessage(String code, Object[] args, boolean htmlEscape) throws
}
/**
- * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance),
- * using the "defaultHtmlEscape" setting.
+ * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance), using the "defaultHtmlEscape" setting.
* @param resolvable the MessageSourceResolvable
* @return the message
* @throws org.springframework.context.NoSuchMessageException if not found
@@ -572,11 +530,9 @@ public String getMessage(MessageSourceResolvable resolvable, boolean htmlEscape)
return (htmlEscape ? HtmlUtils.htmlEscape(msg) : msg);
}
-
/**
- * Retrieve the theme message for the given code.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they
+ * typically denote theme-specific resource paths and not client-visible messages.
* @param code code of the message
* @param defaultMessage String to return if the lookup fails
* @return the message
@@ -586,9 +542,8 @@ public String getThemeMessage(String code, String defaultMessage) {
}
/**
- * Retrieve the theme message for the given code.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they
+ * typically denote theme-specific resource paths and not client-visible messages.
* @param code code of the message
* @param args arguments for the message, or <code>null</code> if none
* @param defaultMessage String to return if the lookup fails
@@ -599,23 +554,21 @@ public String getThemeMessage(String code, Object[] args, String defaultMessage)
}
/**
- * Retrieve the theme message for the given code.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they
+ * typically denote theme-specific resource paths and not client-visible messages.
* @param code code of the message
* @param args arguments for the message as a List, or <code>null</code> if none
* @param defaultMessage String to return if the lookup fails
* @return the message
*/
public String getThemeMessage(String code, List args, String defaultMessage) {
- return getTheme().getMessageSource().getMessage(
- code, (args != null ? args.toArray() : null), defaultMessage, this.locale);
+ return getTheme().getMessageSource().getMessage(code, (args != null ? args.toArray() : null), defaultMessage,
+ this.locale);
}
/**
- * Retrieve the theme message for the given code.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they
+ * typically denote theme-specific resource paths and not client-visible messages.
* @param code code of the message
* @return the message
* @throws org.springframework.context.NoSuchMessageException if not found
@@ -625,9 +578,8 @@ public String getThemeMessage(String code) throws NoSuchMessageException {
}
/**
- * Retrieve the theme message for the given code.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they
+ * typically denote theme-specific resource paths and not client-visible messages.
* @param code code of the message
* @param args arguments for the message, or <code>null</code> if none
* @return the message
@@ -638,23 +590,20 @@ public String getThemeMessage(String code, Object[] args) throws NoSuchMessageEx
}
/**
- * Retrieve the theme message for the given code.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the theme message for the given code. <p>Note that theme messages are never HTML-escaped, as they
+ * typically denote theme-specific resource paths and not client-visible messages.
* @param code code of the message
* @param args arguments for the message as a List, or <code>null</code> if none
* @return the message
* @throws org.springframework.context.NoSuchMessageException if not found
*/
public String getThemeMessage(String code, List args) throws NoSuchMessageException {
- return getTheme().getMessageSource().getMessage(
- code, (args != null ? args.toArray() : null), this.locale);
+ return getTheme().getMessageSource().getMessage(code, (args != null ? args.toArray() : null), this.locale);
}
/**
- * Retrieve the given MessageSourceResolvable in the current theme.
- * <p>Note that theme messages are never HTML-escaped, as they typically
- * denote theme-specific resource paths and not client-visible messages.
+ * Retrieve the given MessageSourceResolvable in the current theme. <p>Note that theme messages are never
+ * HTML-escaped, as they typically denote theme-specific resource paths and not client-visible messages.
* @param resolvable the MessageSourceResolvable
* @return the message
* @throws org.springframework.context.NoSuchMessageException if not found
@@ -663,10 +612,8 @@ public String getThemeMessage(MessageSourceResolvable resolvable) throws NoSuchM
return getTheme().getMessageSource().getMessage(resolvable, this.locale);
}
-
/**
- * Retrieve the Errors instance for the given bind object,
- * using the "defaultHtmlEscape" setting.
+ * Retrieve the Errors instance for the given bind object, using the "defaultHtmlEscape" setting.
* @param name name of the bind object
* @return the Errors instance, or <code>null</code> if not found
*/
@@ -700,8 +647,7 @@ public Errors getErrors(String name, boolean htmlEscape) {
if (htmlEscape && !(errors instanceof EscapedErrors)) {
errors = new EscapedErrors(errors);
put = true;
- }
- else if (!htmlEscape && errors instanceof EscapedErrors) {
+ } else if (!htmlEscape && errors instanceof EscapedErrors) {
errors = ((EscapedErrors) errors).getSource();
put = true;
}
@@ -712,25 +658,21 @@ else if (!htmlEscape && errors instanceof EscapedErrors) {
}
/**
- * Retrieve the model object for the given model name,
- * either from the model or from the request attributes.
+ * Retrieve the model object for the given model name, either from the model or from the request attributes.
* @param modelName the name of the model object
* @return the model object
*/
protected Object getModelObject(String modelName) {
if (this.model != null) {
return this.model.get(modelName);
- }
- else {
+ } else {
return this.request.getAttribute(modelName);
}
}
/**
- * Create a BindStatus for the given bind object,
- * using the "defaultHtmlEscape" setting.
- * @param path the bean and property path for which values and errors
- * will be resolved (e.g. "person.age")
+ * Create a BindStatus for the given bind object, using the "defaultHtmlEscape" setting.
+ * @param path the bean and property path for which values and errors will be resolved (e.g. "person.age")
* @return the new BindStatus instance
* @throws IllegalStateException if no corresponding Errors object found
*/
@@ -739,10 +681,8 @@ public BindStatus getBindStatus(String path) throws IllegalStateException {
}
/**
- * Create a BindStatus for the given bind object,
- * using the "defaultHtmlEscape" setting.
- * @param path the bean and property path for which values and errors
- * will be resolved (e.g. "person.age")
+ * Create a BindStatus for the given bind object, using the "defaultHtmlEscape" setting.
+ * @param path the bean and property path for which values and errors will be resolved (e.g. "person.age")
* @param htmlEscape create a BindStatus with automatic HTML escaping?
* @return the new BindStatus instance
* @throws IllegalStateException if no corresponding Errors object found
@@ -751,10 +691,9 @@ public BindStatus getBindStatus(String path, boolean htmlEscape) throws IllegalS
return new BindStatus(this, path, htmlEscape);
}
-
/**
- * Inner class that isolates the JSTL dependency.
- * Just called to resolve the fallback locale if the JSTL API is present.
+ * Inner class that isolates the JSTL dependency. Just called to resolve the fallback locale if the JSTL API is
+ * present.
*/
private static class JstlLocaleResolver {
| true |
Other | spring-projects | spring-framework | 32ebf18429a179e6bf416db42ae2d474802369ea.json | SPR-5937: add param map to freemarker url macro | org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/support/RequestContextTests.java | @@ -0,0 +1,71 @@
+/*
+ * Copyright 2002-2011 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.web.servlet.support;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.support.GenericWebApplicationContext;
+
+/**
+ * @author Dave Syer
+ *
+ */
+public class RequestContextTests {
+
+ private MockHttpServletRequest request = new MockHttpServletRequest();
+
+ private MockHttpServletResponse response = new MockHttpServletResponse();
+
+ private MockServletContext servletContext = new MockServletContext();
+
+ private Map<String, Object> model = new HashMap<String, Object>();
+
+ @Before
+ public void init() {
+ GenericWebApplicationContext applicationContext = new GenericWebApplicationContext();
+ servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
+ }
+
+ @Test
+ public void testGetContextUrlString() throws Exception {
+ request.setContextPath("foo/");
+ RequestContext context = new RequestContext(request, response, servletContext, model);
+ assertEquals("foo/bar", context.getContextUrl("bar"));
+ }
+
+ @Test
+ public void testGetContextUrlStringMap() throws Exception {
+ request.setContextPath("foo/");
+ RequestContext context = new RequestContext(request, response, servletContext, model);
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("foo", "bar");
+ map.put("spam", "bucket");
+ assertEquals("foo/bar?spam=bucket", context.getContextUrl("{foo}?spam={spam}", map));
+ }
+
+ // TODO: test escaping of query params (not supported by UriTemplate but some features present in UriUtils).
+
+} | true |
Other | spring-projects | spring-framework | c2e62f098ad2ae6e643f56a7429454020ec17294.json | Add ignorable log file to .gitignore | .gitignore | @@ -8,6 +8,7 @@ bin
build.sh
integration-repo
ivy-cache
+jxl.log
jmx.log
org.springframework.jdbc/derby.log
org.springframework.spring-parent/.classpath | true |
Other | spring-projects | spring-framework | c2e62f098ad2ae6e643f56a7429454020ec17294.json | Add ignorable log file to .gitignore | org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java | @@ -41,6 +41,7 @@
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.util.HtmlUtils;
+import org.springframework.web.util.UriTemplate;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.web.util.WebUtils;
@@ -408,6 +409,23 @@ public String getContextUrl(String relativeUrl) {
return url;
}
+ /**
+ * Return a context-aware URl for the given relative URL with placeholders (named keys with braces <code>{}</code>).
+ * @param relativeUrl the relative URL part
+ * @param a map of parameters to insert as placeholders in the url
+ * @return a URL that points back to the server with an absolute path
+ * (also URL-encoded accordingly)
+ */
+ public String getContextUrl(String relativeUrl, Map<String,?> params) {
+ String url = getContextPath() + relativeUrl;
+ UriTemplate template = new UriTemplate(url);
+ url = template.expand(params).toASCIIString();
+ if (this.response != null) {
+ url = this.response.encodeURL(url);
+ }
+ return url;
+ }
+
/**
* Return the request URI of the original request, that is, the invoked URL
* without parameters. This is particularly useful as HTML form action target, | true |
Other | spring-projects | spring-framework | c2e62f098ad2ae6e643f56a7429454020ec17294.json | Add ignorable log file to .gitignore | org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/freemarker/spring.ftl | @@ -86,7 +86,7 @@
* Takes a relative URL and makes it absolute from the server root by
* adding the context root for the web application.
-->
-<#macro url relativeUrl>${springMacroRequestContext.getContextUrl(relativeUrl)}</#macro>
+<#macro url relativeUrl extra...><#if extra?? && extra?size!=0>${springMacroRequestContext.getContextUrl(relativeUrl,extra)}<#else>${springMacroRequestContext.getContextUrl(relativeUrl)}</#if></#macro>
<#--
* bind | true |
Other | spring-projects | spring-framework | c2e62f098ad2ae6e643f56a7429454020ec17294.json | Add ignorable log file to .gitignore | org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/DummyMacroRequestContext.java | @@ -22,6 +22,7 @@
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;
+import org.springframework.web.util.UriTemplate;
/**
* Dummy request context used for VTL and FTL macro tests.
@@ -134,6 +135,14 @@ public String getContextUrl(String relativeUrl) {
return getContextPath() + relativeUrl;
}
+ /**
+ * @see org.springframework.web.servlet.support.RequestContext#getContextUrl(String, Map)
+ */
+ public String getContextUrl(String relativeUrl, Map<String,String> params) {
+ UriTemplate template = new UriTemplate(relativeUrl);
+ return getContextPath() + template.expand(params).toASCIIString();
+ }
+
/**
* @see org.springframework.web.servlet.support.RequestContext#getBindStatus(String)
*/ | true |
Other | spring-projects | spring-framework | c2e62f098ad2ae6e643f56a7429454020ec17294.json | Add ignorable log file to .gitignore | org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java | @@ -16,23 +16,28 @@
package org.springframework.web.servlet.view.freemarker;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.FileWriter;
+import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
-import freemarker.template.Configuration;
-import freemarker.template.Template;
-import freemarker.template.TemplateModel;
-import freemarker.template.SimpleHash;
-import freemarker.template.TemplateException;
-import junit.framework.TestCase;
-
+import org.junit.Before;
+import org.junit.Test;
import org.springframework.beans.TestBean;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.FileSystemResource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
+import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
@@ -42,16 +47,20 @@
import org.springframework.web.servlet.theme.FixedThemeResolver;
import org.springframework.web.servlet.view.DummyMacroRequestContext;
+import freemarker.template.Configuration;
+import freemarker.template.SimpleHash;
+import freemarker.template.Template;
+import freemarker.template.TemplateException;
+
/**
* @author Darren Davison
* @author Juergen Hoeller
* @since 25.01.2005
*/
-public class FreeMarkerMacroTests extends TestCase {
+public class FreeMarkerMacroTests {
private static final String TEMPLATE_FILE = "test.ftl";
-
private StaticWebApplicationContext wac;
private MockHttpServletRequest request;
@@ -60,14 +69,14 @@ public class FreeMarkerMacroTests extends TestCase {
private FreeMarkerConfigurer fc;
-
+ @Before
public void setUp() throws Exception {
wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
- //final Template expectedTemplate = new Template();
+ // final Template expectedTemplate = new Template();
fc = new FreeMarkerConfigurer();
- fc.setPreferFileSystemAccess(false);
+ fc.setTemplateLoaderPaths(new String[] { "classpath:/", "file://" + System.getProperty("java.io.tmpdir") });
fc.afterPropertiesSet();
wac.getDefaultListableBeanFactory().registerSingleton("freeMarkerConfigurer", fc);
@@ -80,10 +89,12 @@ public void setUp() throws Exception {
response = new MockHttpServletResponse();
}
+ @Test
public void testExposeSpringMacroHelpers() throws Exception {
FreeMarkerView fv = new FreeMarkerView() {
@Override
- protected void processTemplate(Template template, SimpleHash fmModel, HttpServletResponse response) throws TemplateException {
+ protected void processTemplate(Template template, SimpleHash fmModel, HttpServletResponse response)
+ throws TemplateException {
Map model = fmModel.toMap();
assertTrue(model.get(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE) instanceof RequestContext);
RequestContext rc = (RequestContext) model.get(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE);
@@ -101,6 +112,7 @@ protected void processTemplate(Template template, SimpleHash fmModel, HttpServle
fv.render(model, request, response);
}
+ @Test
public void testSpringMacroRequestContextAttributeUsed() {
final String helperTool = "wrongType";
@@ -119,14 +131,143 @@ protected void processTemplate(Template template, SimpleHash model, HttpServletR
try {
fv.render(model, request, response);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
assertTrue(ex instanceof ServletException);
assertTrue(ex.getMessage().contains(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE));
}
}
- public void testAllMacros() throws Exception {
+ @Test
+ public void testName() throws Exception {
+ assertEquals("Darren", getMacroOutput("NAME"));
+ }
+
+ @Test
+ public void testAge() throws Exception {
+ assertEquals("99", getMacroOutput("AGE"));
+ }
+
+ @Test
+ public void testMessage() throws Exception {
+ assertEquals("Howdy Mundo", getMacroOutput("MESSAGE"));
+ }
+
+ @Test
+ public void testDefaultMessage() throws Exception {
+ assertEquals("hi planet", getMacroOutput("DEFAULTMESSAGE"));
+ }
+
+ @Test
+ public void testMessageArgs() throws Exception {
+ assertEquals("Howdy[World]", getMacroOutput("MESSAGEARGS"));
+ }
+
+ @Test
+ public void testMessageArgsWithDefaultMessage() throws Exception {
+ assertEquals("Hi", getMacroOutput("MESSAGEARGSWITHDEFAULTMESSAGE"));
+ }
+
+ @Test
+ public void testTheme() throws Exception {
+ assertEquals("Howdy! Mundo!", getMacroOutput("THEME"));
+ }
+
+ @Test
+ public void testDefaultTheme() throws Exception {
+ assertEquals("hi! planet!", getMacroOutput("DEFAULTTHEME"));
+ }
+
+ @Test
+ public void testThemeArgs() throws Exception {
+ assertEquals("Howdy![World]", getMacroOutput("THEMEARGS"));
+ }
+
+ @Test
+ public void testThemeArgsWithDefaultMessage() throws Exception {
+ assertEquals("Hi!", getMacroOutput("THEMEARGSWITHDEFAULTMESSAGE"));
+ }
+
+ @Test
+ public void testUrl() throws Exception {
+ assertEquals("/springtest/aftercontext.html", getMacroOutput("URL"));
+ }
+
+ @Test
+ public void testUrlParams() throws Exception {
+ assertEquals("/springtest/aftercontext/bar?spam=bucket", getMacroOutput("URLPARAMS"));
+ }
+
+ @Test
+ public void testForm1() throws Exception {
+ assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >", getMacroOutput("FORM1"));
+ }
+
+ @Test
+ public void testForm2() throws Exception {
+ assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" class=\"myCssClass\" >",
+ getMacroOutput("FORM2"));
+ }
+
+ @Test
+ public void testForm3() throws Exception {
+ assertEquals("<textarea id=\"name\" name=\"name\" >Darren</textarea>", getMacroOutput("FORM3"));
+ }
+
+ @Test
+ public void testForm4() throws Exception {
+ assertEquals("<textarea id=\"name\" name=\"name\" rows=10 cols=30>Darren</textarea>", getMacroOutput("FORM4"));
+ }
+
+ // TODO verify remaining output (fix whitespace)
+ @Test
+ public void testForm9() throws Exception {
+ assertEquals("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >", getMacroOutput("FORM9"));
+ }
+
+ @Test
+ public void testForm10() throws Exception {
+ assertEquals("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >",
+ getMacroOutput("FORM10"));
+ }
+
+ @Test
+ public void testForm11() throws Exception {
+ assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >", getMacroOutput("FORM11"));
+ }
+
+ @Test
+ public void testForm12() throws Exception {
+ assertEquals("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >",
+ getMacroOutput("FORM12"));
+ }
+
+ @Test
+ public void testForm13() throws Exception {
+ assertEquals("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >", getMacroOutput("FORM13"));
+ }
+
+ @Test
+ public void testForm15() throws Exception {
+ String output = getMacroOutput("FORM15");
+ assertTrue("Wrong output: " + output, output.startsWith("<input type=\"hidden\" name=\"_name\" value=\"on\"/>"));
+ assertTrue("Wrong output: " + output, output.contains("<input type=\"checkbox\" id=\"name\" name=\"name\" />"));
+ }
+
+ @Test
+ public void testForm16() throws Exception {
+ String output = getMacroOutput("FORM16");
+ assertTrue("Wrong output: " + output, output.startsWith("<input type=\"hidden\" name=\"_jedi\" value=\"on\"/>"));
+ assertTrue("Wrong output: " + output, output.contains("<input type=\"checkbox\" id=\"jedi\" name=\"jedi\" checked=\"checked\" />"));
+ }
+
+ private String getMacroOutput(String name) throws Exception {
+
+ String macro = fetchMacro(name);
+ assertNotNull(macro);
+
+ FileSystemResource resource = new FileSystemResource(System.getProperty("java.io.tmpdir") + "/tmp.ftl");
+ FileCopyUtils.copy("<#import \"spring.ftl\" as spring />\n" + macro, new FileWriter(resource.getPath()));
+
DummyMacroRequestContext rc = new DummyMacroRequestContext(request);
Map msgMap = new HashMap();
msgMap.put("hello", "Howdy");
@@ -153,13 +294,13 @@ public void testAllMacros() throws Exception {
Map model = new HashMap();
model.put("command", tb);
model.put("springMacroRequestContext", rc);
- model.put("msgArgs", new Object[] {"World"});
+ model.put("msgArgs", new Object[] { "World" });
model.put("nameOptionMap", names);
model.put("options", names.values());
FreeMarkerView view = new FreeMarkerView();
view.setBeanName("myView");
- view.setUrl("test.ftl");
+ view.setUrl("tmp.ftl");
view.setExposeSpringMacroHelpers(false);
view.setConfiguration(config);
view.setServletContext(new MockServletContext());
@@ -168,36 +309,20 @@ public void testAllMacros() throws Exception {
// tokenize output and ignore whitespace
String output = response.getContentAsString();
- System.out.println(output);
- String[] tokens = StringUtils.tokenizeToStringArray(output, "\t\n");
-
- for (int i = 0; i < tokens.length; i++) {
- if (tokens[i].equals("NAME")) assertEquals("Darren", tokens[i + 1]);
- if (tokens[i].equals("AGE")) assertEquals("99", tokens[i + 1]);
- if (tokens[i].equals("MESSAGE")) assertEquals("Howdy Mundo", tokens[i + 1]);
- if (tokens[i].equals("DEFAULTMESSAGE")) assertEquals("hi planet", tokens[i + 1]);
- if (tokens[i].equals("MESSAGEARGS")) assertEquals("Howdy[World]", tokens[i + 1]);
- if (tokens[i].equals("MESSAGEARGSWITHDEFAULTMESSAGE")) assertEquals("Hi", tokens[i + 1]);
- if (tokens[i].equals("THEME")) assertEquals("Howdy! Mundo!", tokens[i + 1]);
- if (tokens[i].equals("DEFAULTTHEME")) assertEquals("hi! planet!", tokens[i + 1]);
- if (tokens[i].equals("THEMEARGS")) assertEquals("Howdy![World]", tokens[i + 1]);
- if (tokens[i].equals("THEMEARGSWITHDEFAULTMESSAGE")) assertEquals("Hi!", tokens[i + 1]);
- if (tokens[i].equals("URL")) assertEquals("/springtest/aftercontext.html", tokens[i + 1]);
- if (tokens[i].equals("FORM1")) assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM2")) assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" class=\"myCssClass\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM3")) assertEquals("<textarea id=\"name\" name=\"name\" >Darren</textarea>", tokens[i + 1]);
- if (tokens[i].equals("FORM4")) assertEquals("<textarea id=\"name\" name=\"name\" rows=10 cols=30>Darren</textarea>", tokens[i + 1]);
- //TODO verify remaining output (fix whitespace)
- if (tokens[i].equals("FORM9")) assertEquals("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM10")) assertEquals("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM11")) assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM12")) assertEquals("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM13")) assertEquals("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >", tokens[i + 1]);
- if (tokens[i].equals("FORM15")) assertEquals("<input type=\"hidden\" name=\"_name\" value=\"on\"/>", tokens[i + 1]);
- if (tokens[i].equals("FORM15")) assertEquals("<input type=\"checkbox\" id=\"name\" name=\"name\" />", tokens[i + 2]);
- if (tokens[i].equals("FORM16")) assertEquals("<input type=\"hidden\" name=\"_jedi\" value=\"on\"/>", tokens[i + 1]);
- if (tokens[i].equals("FORM16")) assertEquals("<input type=\"checkbox\" id=\"jedi\" name=\"jedi\" checked=\"checked\" />", tokens[i + 2]);
+ return output.trim();
+ }
+
+ private String fetchMacro(String name) throws Exception {
+ ClassPathResource resource = new ClassPathResource("test.ftl", getClass());
+ assertTrue(resource.exists());
+ String all = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
+ String[] macros = StringUtils.delimitedListToStringArray(all, "\n\n");
+ for (String macro : macros) {
+ if (macro.startsWith(name)) {
+ return macro.substring(macro.indexOf("\n")).trim();
+ }
}
+ return null;
}
} | true |
Other | spring-projects | spring-framework | c2e62f098ad2ae6e643f56a7429454020ec17294.json | Add ignorable log file to .gitignore | org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/freemarker/test.ftl | @@ -36,6 +36,9 @@ THEMEARGSWITHDEFAULTMESSAGE
URL
<@spring.url "/aftercontext.html"/>
+URLPARAMS
+<@spring.url relativeUrl="/aftercontext/{foo}?spam={spam}" foo="bar" spam="bucket"/>
+
FORM1
<@spring.formInput "command.name", ""/>
| true |
Other | spring-projects | spring-framework | 1bf8634db1c025198e7383834079d464cb05162f.json | Fix broken links in ref docs | spring-framework-reference/src/beans.xml | @@ -548,7 +548,7 @@ List userList service.getUsernameList();
or id is supplied explicitly, the container generates a unique name for
that bean. However, if you want to refer to that bean by name, through
the use of the <literal>ref</literal> element or <link lang=""
- linkend="beans-servicelocation">Service Location</link> style lookup,
+ linkend="beans-servicelocator">Service Locator</link> style lookup,
you must provide a name. Motivations for not supplying a name are
related to using <link linkend="beans-inner-beans">inner beans</link>
and <link linkend="beans-factory-autowire">autowiring | true |
Other | spring-projects | spring-framework | 1bf8634db1c025198e7383834079d464cb05162f.json | Fix broken links in ref docs | spring-framework-reference/src/cache.xml | @@ -98,7 +98,7 @@ public Book findBook(ISBN isbn) {...}]]></programlisting>
In fact, depending on the JVM implementation or running conditions, the same hashCode can be reused for different objects, in the same VM instance.</para>
<para>To provide a different <emphasis>default</emphasis> key generator, one needs to implement the <interfacename>org.springframework.cache.KeyGenerator</interfacename> interface.
- Once <link linkend="cache-configuration">configured</link>, the generator will be used for each declaration that doesn not specify its own key generation strategy (see below).
+ Once configured, the generator will be used for each declaration that doesn not specify its own key generation strategy (see below).
</para>
</section>
@@ -442,4 +442,4 @@ public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)]]><
can fill in this small configuration gap.</para>
</section>
-</chapter>
\ No newline at end of file
+</chapter>
| true |
Other | spring-projects | spring-framework | 1bf8634db1c025198e7383834079d464cb05162f.json | Fix broken links in ref docs | spring-framework-reference/src/validation.xml | @@ -1101,7 +1101,7 @@ public interface ConversionService {
</bean>]]></programlisting>
<para>It is also common to use a ConversionService within a Spring MVC
- application. See <xref linkend="format-configuring-FormatterRegistry"/>
+ application. See <xref linkend="format-configuring-FormattingConversionService"/>
for details on use with
<literal><mvc:annotation-driven/></literal>.</para>
@@ -1415,7 +1415,7 @@ public interface FormatterRegistrar {
</para>
</section>
- <section id="format-configuring-FormattingConverionService">
+ <section id="format-configuring-FormattingConversionService">
<title>Configuring Formatting in Spring MVC</title>
<para> In a Spring MVC application, you may configure a custom | true |
Other | spring-projects | spring-framework | 16fc083310d5414f2fbca205f8de8a2c25082961.json | SPR-8391 Minor documentation fixes | spring-framework-reference/src/mvc.xml | @@ -237,7 +237,7 @@
<imagedata align="center" fileref="images/mvc.png" format="PNG" />
</imageobject>
- <caption><para>The requesting processing workflow in Spring Web MVC
+ <caption><para>The request processing workflow in Spring Web MVC
(high level)</para></caption>
</mediaobject></para>
@@ -843,7 +843,7 @@ public String findOwner(<emphasis role="bold">@PathVariable</emphasis>("ownerId"
<programlisting language="java">@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)
public String findPet(<emphasis role="bold">@PathVariable</emphasis> String ownerId, <emphasis
role="bold">@PathVariable</emphasis> String petId, Model model) {
- Owner owner = ownerService.findOwner(ownderId);
+ Owner owner = ownerService.findOwner(ownerId);
Pet pet = owner.getPet(petId);
model.addAttribute("pet", pet);
return "displayPet";
@@ -3208,21 +3208,22 @@ public class SimpleController {
</sidebar>
<para>The strategy for generating a name after adding a
- <interfacename>Set</interfacename>, <interfacename>List</interfacename>
- or array object is to peek into the collection, take the short class
- name of the first object in the collection, and use that with
- <literal>List</literal> appended to the name. Some examples will make
- the semantics of name generation for collections clearer...</para>
+ <interfacename>Set</interfacename> or a <interfacename>List</interfacename>
+ is to peek into the collection, take the short class name of the first object
+ in the collection, and use that with <literal>List</literal> appended to the
+ name. The same applies to arrays although with arrays it is not necessary to
+ peek into the array contents. A few examples will make the semantics of name
+ generation for collections clearer:</para>
<itemizedlist>
<listitem>
- <para>An <classname>x.y.User[]</classname> array with one or more
+ <para>An <classname>x.y.User[]</classname> array with zero or more
<classname>x.y.User</classname> elements added will have the name
<literal>userList</literal> generated.</para>
</listitem>
<listitem>
- <para>An <classname>x.y.Foo[]</classname> array with one or more
+ <para>An <classname>x.y.Foo[]</classname> array with zero or more
<classname>x.y.User</classname> elements added will have the name
<literal>fooList</literal> generated.</para>
</listitem> | false |
Other | spring-projects | spring-framework | 2bc3527f76247a3b8fd81ba5373b4b155e3a48b8.json | Consolidate annotation processing constants
Consolidating internal bean name and aspect class name constats within
AnnotationConfigUtils to allow access from both the context.config
and context.annotation packages without creating a relationship between
the two of them (they are unrelated leaf nodes in the packaging
currently).
The .transaction module does not have a similar utils class and already
has a relationship from transaction.config -> transaction.annotation,
so placing the constants in .annotation.TransactionManagementCapability
to be referenced by .config.AnnotationDrivenBeanDefinitionParser | org.springframework.context/src/main/java/org/springframework/cache/config/AnnotationDrivenCacheBeanDefinitionParser.java | @@ -16,6 +16,10 @@
package org.springframework.cache.config;
+import static org.springframework.context.annotation.AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME;
+import static org.springframework.context.annotation.AnnotationConfigUtils.CACHE_ASPECT_BEAN_NAME;
+import static org.springframework.context.annotation.AnnotationConfigUtils.CACHE_ASPECT_CLASS_NAME;
+
import org.springframework.aop.config.AopNamespaceUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
@@ -49,18 +53,6 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
private static final String DEFAULT_CACHE_MANAGER_BEAN_NAME = "cacheManager";
- /**
- * The bean name of the internally managed cache advisor (mode="proxy").
- */
- public static final String CACHE_ADVISOR_BEAN_NAME = "org.springframework.cache.config.internalCacheAdvisor";
-
- /**
- * The bean name of the internally managed cache aspect (mode="aspectj").
- */
- public static final String CACHE_ASPECT_BEAN_NAME = "org.springframework.cache.config.internalCacheAspect";
-
- private static final String CACHE_ASPECT_CLASS_NAME = "org.springframework.cache.aspectj.AnnotationCacheAspect";
-
/**
* Parses the '<code><cache:annotation-driven/></code>' tag. Will
* {@link AopNamespaceUtils#registerAutoProxyCreatorIfNecessary register an AutoProxyCreator}
| true |
Other | spring-projects | spring-framework | 2bc3527f76247a3b8fd81ba5373b4b155e3a48b8.json | Consolidate annotation processing constants
Consolidating internal bean name and aspect class name constats within
AnnotationConfigUtils to allow access from both the context.config
and context.annotation packages without creating a relationship between
the two of them (they are unrelated leaf nodes in the packaging
currently).
The .transaction module does not have a similar utils class and already
has a relationship from transaction.config -> transaction.annotation,
so placing the constants in .annotation.TransactionManagementCapability
to be referenced by .config.AnnotationDrivenBeanDefinitionParser | org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java | @@ -70,6 +70,48 @@ public class AnnotationConfigUtils {
public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalCommonAnnotationProcessor";
+ /**
+ * The bean name of the internally managed Scheduled annotation processor.
+ */
+ public static final String SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalScheduledAnnotationProcessor";
+
+ /**
+ * The bean name of the internally managed Async annotation processor.
+ */
+ public static final String ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalAsyncAnnotationProcessor";
+
+ /**
+ * The bean name of the internally managed AspectJ async execution aspect.
+ */
+ public static final String ASYNC_EXECUTION_ASPECT_BEAN_NAME =
+ "org.springframework.scheduling.config.internalAsyncExecutionAspect";
+
+ /**
+ * The class name of the AspectJ async execution aspect.
+ */
+ public static final String ASYNC_EXECUTION_ASPECT_CLASS_NAME =
+ "org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect";
+
+ /**
+ * The bean name of the internally managed cache advisor.
+ */
+ public static final String CACHE_ADVISOR_BEAN_NAME =
+ "org.springframework.cache.config.internalCacheAdvisor";
+
+ /**
+ * The bean name of the internally managed cache aspect.
+ */
+ public static final String CACHE_ASPECT_BEAN_NAME =
+ "org.springframework.cache.config.internalCacheAspect";
+
+ /**
+ * The class name of the AspectJ caching aspect.
+ */
+ public static final String CACHE_ASPECT_CLASS_NAME =
+ "org.springframework.cache.aspectj.AnnotationCacheAspect";
+
/**
* The bean name of the internally managed JPA annotation processor.
*/ | true |
Other | spring-projects | spring-framework | 2bc3527f76247a3b8fd81ba5373b4b155e3a48b8.json | Consolidate annotation processing constants
Consolidating internal bean name and aspect class name constats within
AnnotationConfigUtils to allow access from both the context.config
and context.annotation packages without creating a relationship between
the two of them (they are unrelated leaf nodes in the packaging
currently).
The .transaction module does not have a similar utils class and already
has a relationship from transaction.config -> transaction.annotation,
so placing the constants in .annotation.TransactionManagementCapability
to be referenced by .config.AnnotationDrivenBeanDefinitionParser | org.springframework.context/src/main/java/org/springframework/scheduling/config/AnnotationDrivenBeanDefinitionParser.java | @@ -27,6 +27,7 @@
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
+import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.util.StringUtils;
/**
@@ -35,30 +36,37 @@
* @author Mark Fisher
* @author Juergen Hoeller
* @author Ramnivas Laddad
+ * @author Chris Beams
* @since 3.0
*/
public class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
/**
* The bean name of the internally managed async annotation processor (mode="proxy").
+ * @deprecated as of Spring 3.1 in favor of
+ * {@link AnnotationConfigUtils#ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME}
*/
+ @Deprecated
public static final String ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME =
- "org.springframework.scheduling.annotation.internalAsyncAnnotationProcessor";
+ AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME;
/**
* The bean name of the internally managed transaction aspect (mode="aspectj").
+ * @deprecated as of Spring 3.1 in favor of
+ * {@link AnnotationConfigUtils#ASYNC_EXECUTION_ASPECT_BEAN_NAME}
*/
+ @Deprecated
public static final String ASYNC_EXECUTION_ASPECT_BEAN_NAME =
- "org.springframework.scheduling.config.internalAsyncExecutionAspect";
-
- private static final String ASYNC_EXECUTION_ASPECT_CLASS_NAME =
- "org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect";
+ AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME;
/**
* The bean name of the internally managed scheduled annotation processor.
+ * @deprecated as of Spring 3.1 in favor of
+ * {@link AnnotationConfigUtils#SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME}
*/
+ @Deprecated
public static final String SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME =
- "org.springframework.scheduling.annotation.internalScheduledAnnotationProcessor";
+ AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME;
public BeanDefinition parse(Element element, ParserContext parserContext) {
@@ -78,7 +86,7 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
}
else {
// mode="proxy"
- if (registry.containsBeanDefinition(ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)) {
+ if (registry.containsBeanDefinition(AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)) {
parserContext.getReaderContext().error(
"Only one AsyncAnnotationBeanPostProcessor may exist within the context.", source);
}
@@ -93,11 +101,11 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
if (Boolean.valueOf(element.getAttribute(AopNamespaceUtils.PROXY_TARGET_CLASS_ATTRIBUTE))) {
builder.addPropertyValue("proxyTargetClass", true);
}
- registerPostProcessor(parserContext, builder, ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME);
+ registerPostProcessor(parserContext, builder, AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME);
}
}
- if (registry.containsBeanDefinition(SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
+ if (registry.containsBeanDefinition(AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
parserContext.getReaderContext().error(
"Only one ScheduledAnnotationBeanPostProcessor may exist within the context.", source);
}
@@ -109,7 +117,7 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
if (StringUtils.hasText(scheduler)) {
builder.addPropertyReference("scheduler", scheduler);
}
- registerPostProcessor(parserContext, builder, SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME);
+ registerPostProcessor(parserContext, builder, AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME);
}
// Finally register the composite component.
@@ -119,16 +127,17 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
}
private void registerAsyncExecutionAspect(Element element, ParserContext parserContext) {
- if (!parserContext.getRegistry().containsBeanDefinition(ASYNC_EXECUTION_ASPECT_BEAN_NAME)) {
+ if (!parserContext.getRegistry().containsBeanDefinition(AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
- ASYNC_EXECUTION_ASPECT_CLASS_NAME);
+ AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_CLASS_NAME);
builder.setFactoryMethod("aspectOf");
String executor = element.getAttribute("executor");
if (StringUtils.hasText(executor)) {
builder.addPropertyReference("executor", executor);
}
parserContext.registerBeanComponent(
- new BeanComponentDefinition(builder.getBeanDefinition(), ASYNC_EXECUTION_ASPECT_BEAN_NAME));
+ new BeanComponentDefinition(builder.getBeanDefinition(),
+ AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME));
}
}
| true |
Other | spring-projects | spring-framework | 2bc3527f76247a3b8fd81ba5373b4b155e3a48b8.json | Consolidate annotation processing constants
Consolidating internal bean name and aspect class name constats within
AnnotationConfigUtils to allow access from both the context.config
and context.annotation packages without creating a relationship between
the two of them (they are unrelated leaf nodes in the packaging
currently).
The .transaction module does not have a similar utils class and already
has a relationship from transaction.config -> transaction.annotation,
so placing the constants in .annotation.TransactionManagementCapability
to be referenced by .config.AnnotationDrivenBeanDefinitionParser | org.springframework.context/src/test/java/org/springframework/scheduling/config/AnnotationDrivenBeanDefinitionParserTests.java | @@ -24,6 +24,7 @@
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
@@ -42,27 +43,26 @@ public void setup() {
@Test
public void asyncPostProcessorRegistered() {
- assertTrue(context.containsBean(
- AnnotationDrivenBeanDefinitionParser.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME));
+ assertTrue(context.containsBean(AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME));
}
@Test
public void scheduledPostProcessorRegistered() {
assertTrue(context.containsBean(
- AnnotationDrivenBeanDefinitionParser.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME));
+ AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
@Test
public void asyncPostProcessorExecutorReference() {
Object executor = context.getBean("testExecutor");
- Object postProcessor = context.getBean(AnnotationDrivenBeanDefinitionParser.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME);
+ Object postProcessor = context.getBean(AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME);
assertSame(executor, new DirectFieldAccessor(postProcessor).getPropertyValue("executor"));
}
@Test
public void scheduledPostProcessorSchedulerReference() {
Object scheduler = context.getBean("testScheduler");
- Object postProcessor = context.getBean(AnnotationDrivenBeanDefinitionParser.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME);
+ Object postProcessor = context.getBean(AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME);
assertSame(scheduler, new DirectFieldAccessor(postProcessor).getPropertyValue("scheduler"));
}
| true |
Other | spring-projects | spring-framework | 2bc3527f76247a3b8fd81ba5373b4b155e3a48b8.json | Consolidate annotation processing constants
Consolidating internal bean name and aspect class name constats within
AnnotationConfigUtils to allow access from both the context.config
and context.annotation packages without creating a relationship between
the two of them (they are unrelated leaf nodes in the packaging
currently).
The .transaction module does not have a similar utils class and already
has a relationship from transaction.config -> transaction.annotation,
so placing the constants in .annotation.TransactionManagementCapability
to be referenced by .config.AnnotationDrivenBeanDefinitionParser | org.springframework.transaction/src/main/java/org/springframework/transaction/config/AnnotationDrivenBeanDefinitionParser.java | @@ -28,6 +28,7 @@
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.config.AbstractSpecificationBeanDefinitionParser;
import org.springframework.context.config.FeatureSpecification;
+import org.springframework.transaction.annotation.TransactionManagementCapability;
import org.w3c.dom.Element;
/**
@@ -46,21 +47,26 @@
* @author Rob Harrop
* @author Chris Beams
* @since 2.0
- * @see TxAnnotationDriven
*/
class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
/**
* The bean name of the internally managed transaction advisor (mode="proxy").
+ * @deprecated as of Spring 3.1 in favor of
+ * {@link TransactionManagementCapability#TRANSACTION_ADVISOR_BEAN_NAME}
*/
+ @Deprecated
public static final String TRANSACTION_ADVISOR_BEAN_NAME =
- TxAnnotationDrivenExecutor.TRANSACTION_ADVISOR_BEAN_NAME;
+ TransactionManagementCapability.TRANSACTION_ADVISOR_BEAN_NAME;
/**
* The bean name of the internally managed transaction aspect (mode="aspectj").
+ * @deprecated as of Spring 3.1 in favor of
+ * {@link TransactionManagementCapability#TRANSACTION_ASPECT_BEAN_NAME}
*/
+ @Deprecated
public static final String TRANSACTION_ASPECT_BEAN_NAME =
- TxAnnotationDrivenExecutor.TRANSACTION_ASPECT_BEAN_NAME;
+ TransactionManagementCapability.TRANSACTION_ASPECT_BEAN_NAME;
/** | true |
Other | spring-projects | spring-framework | 9a271ce6c92695b9421aa603c9aa56e805c7920c.json | Introduce ImportSelector interface
Allows @Enable* a layer of indirection for deciding which @Configuration
class(es) to @Import.
The @Import annotation may now accept @Configuration class literals
and/or ImportSelector class literals. | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java | @@ -27,6 +27,7 @@
import java.util.Set;
import java.util.Stack;
+import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.parsing.Location;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.beans.factory.parsing.ProblemReporter;
@@ -37,6 +38,7 @@
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
+import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.util.StringUtils;
/**
@@ -142,7 +144,7 @@ protected void doProcessConfigurationClass(ConfigurationClass configClass, Annot
List<Map<String, Object>> allImportAttribs =
AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
for (Map<String, Object> importAttribs : allImportAttribs) {
- processImport(configClass, (String[]) importAttribs.get("value"));
+ processImport(configClass, (String[]) importAttribs.get("value"), true);
}
if (metadata.isAnnotated(ImportResource.class.getName())) {
@@ -162,16 +164,29 @@ protected void doProcessConfigurationClass(ConfigurationClass configClass, Annot
}
}
- private void processImport(ConfigurationClass configClass, String[] classesToImport) throws IOException {
- if (this.importStack.contains(configClass)) {
+ private void processImport(ConfigurationClass configClass, String[] classesToImport, boolean checkForCircularImports) throws IOException {
+ if (checkForCircularImports && this.importStack.contains(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack, configClass.getMetadata()));
}
else {
this.importStack.push(configClass);
- for (String classToImport : classesToImport) {
- this.importStack.registerImport(configClass.getMetadata().getClassName(), classToImport);
- MetadataReader reader = this.metadataReaderFactory.getMetadataReader(classToImport);
- processConfigurationClass(new ConfigurationClass(reader, null));
+ AnnotationMetadata importingClassMetadata = configClass.getMetadata();
+ for (String candidate : classesToImport) {
+ MetadataReader reader = this.metadataReaderFactory.getMetadataReader(candidate);
+ if (new AssignableTypeFilter(ImportSelector.class).match(reader, metadataReaderFactory)) {
+ // the candidate class is an ImportSelector -> delegate to it to determine imports
+ try {
+ ImportSelector selector = BeanUtils.instantiateClass(Class.forName(candidate), ImportSelector.class);
+ processImport(configClass, selector.selectImports(importingClassMetadata), false);
+ } catch (ClassNotFoundException ex) {
+ throw new IllegalStateException(ex);
+ }
+ }
+ else {
+ // the candidate class not an ImportSelector -> process it as a @Configuration class
+ this.importStack.registerImport(importingClassMetadata.getClassName(), candidate);
+ processConfigurationClass(new ConfigurationClass(reader, null));
+ }
}
this.importStack.pop();
} | true |
Other | spring-projects | spring-framework | 9a271ce6c92695b9421aa603c9aa56e805c7920c.json | Introduce ImportSelector interface
Allows @Enable* a layer of indirection for deciding which @Configuration
class(es) to @Import.
The @Import annotation may now accept @Configuration class literals
and/or ImportSelector class literals. | org.springframework.context/src/main/java/org/springframework/context/annotation/ImportSelector.java | @@ -0,0 +1,40 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import org.springframework.core.type.AnnotationMetadata;
+
+
+/**
+ * Interface to be implemented by types that determine
+ * which @{@link Configuration} class(es) should be imported based on
+ * a given selection criteria, usually an annotation attribute.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ * @see Import
+ */
+public interface ImportSelector {
+
+ /**
+ * Select and return the names of which class(es) should be imported.
+ * @param importingClassMetadata the AnnotationMetodata of the
+ * importing @{@link Configuration} class.
+ */
+ String[] selectImports(AnnotationMetadata importingClassMetadata);
+
+} | true |
Other | spring-projects | spring-framework | cdb01cbd3795f273b751d0f0a45caa22d07c62da.json | Introduce ImportAware interface
@Configuration classes may implement ImportAware in order to be injected
with the AnnotationMetadata of their @Import'ing class.
Includes the introduction of a new PriorityOrdered
ImportAwareBeanPostProcessor that handles injection of the
importing class metadata. | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java | @@ -19,6 +19,7 @@
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
@@ -62,7 +63,7 @@ class ConfigurationClassParser {
private final ProblemReporter problemReporter;
- private final Stack<ConfigurationClass> importStack = new ImportStack();
+ private final ImportStack importStack = new ImportStack();
private final Set<ConfigurationClass> configurationClasses =
new LinkedHashSet<ConfigurationClass>();
@@ -168,6 +169,7 @@ private void processImport(ConfigurationClass configClass, String[] classesToImp
else {
this.importStack.push(configClass);
for (String classToImport : classesToImport) {
+ this.importStack.registerImport(configClass.getMetadata().getClassName(), classToImport);
MetadataReader reader = this.metadataReaderFactory.getMetadataReader(classToImport);
processConfigurationClass(new ConfigurationClass(reader, null));
}
@@ -189,9 +191,28 @@ public Set<ConfigurationClass> getConfigurationClasses() {
return this.configurationClasses;
}
+ public ImportRegistry getImportRegistry() {
+ return this.importStack;
+ }
+
+
+ interface ImportRegistry {
+ String getImportingClassFor(String importedClass);
+ }
+
@SuppressWarnings("serial")
- private static class ImportStack extends Stack<ConfigurationClass> {
+ private static class ImportStack extends Stack<ConfigurationClass> implements ImportRegistry {
+
+ private Map<String, String> imports = new HashMap<String, String>();
+
+ public String getImportingClassFor(String importedClass) {
+ return imports.get(importedClass);
+ }
+
+ public void registerImport(String importingClass, String importedClass) {
+ imports.put(importedClass, importingClass);
+ }
/**
* Simplified contains() implementation that tests to see if any {@link ConfigurationClass} | true |
Other | spring-projects | spring-framework | cdb01cbd3795f273b751d0f0a45caa22d07c62da.json | Introduce ImportAware interface
@Configuration classes may implement ImportAware in order to be injected
with the AnnotationMetadata of their @Import'ing class.
Includes the introduction of a new PriorityOrdered
ImportAwareBeanPostProcessor that handles injection of the
importing class metadata. | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java | @@ -24,27 +24,38 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanDefinitionStoreException;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
+import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
import org.springframework.beans.factory.parsing.PassThroughSourceExtractor;
import org.springframework.beans.factory.parsing.ProblemReporter;
import org.springframework.beans.factory.parsing.SourceExtractor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
+import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
+import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
+import org.springframework.context.annotation.ConfigurationClassParser.ImportRegistry;
import org.springframework.core.Ordered;
+import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
+import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
+import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -147,6 +158,7 @@ public void setEnvironment(Environment environment) {
* Derive further bean definitions from the configuration classes in the registry.
*/
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
+ BeanDefinitionReaderUtils.registerWithGeneratedName(new RootBeanDefinition(ImportAwareBeanPostProcessor.class), registry);
if (this.postProcessBeanDefinitionRegistryCalled) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called for this post-processor");
@@ -231,6 +243,13 @@ public void processConfigBeanDefinitions(ConfigurationClassParser parser, Config
// Read the model and create bean definitions based on its content
reader.loadBeanDefinitions(parser.getConfigurationClasses());
+
+ // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
+ if (registry instanceof SingletonBeanRegistry) {
+ if (!((SingletonBeanRegistry) registry).containsSingleton("importRegistry")) {
+ ((SingletonBeanRegistry) registry).registerSingleton("importRegistry", parser.getImportRegistry());
+ }
+ }
}
/**
@@ -278,4 +297,41 @@ public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFact
}
}
+
+ private static class ImportAwareBeanPostProcessor implements PriorityOrdered, BeanFactoryAware, BeanPostProcessor {
+
+ private BeanFactory beanFactory;
+
+ public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
+ this.beanFactory = beanFactory;
+ }
+
+ public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
+ if (bean instanceof ImportAware) {
+ ImportRegistry importRegistry = beanFactory.getBean(ImportRegistry.class);
+ String importingClass = importRegistry.getImportingClassFor(bean.getClass().getSuperclass().getName());
+ if (importingClass != null) {
+ try {
+ AnnotationMetadata metadata = new SimpleMetadataReaderFactory().getMetadataReader(importingClass).getAnnotationMetadata();
+ ((ImportAware) bean).setImportMetadata(metadata);
+ } catch (IOException ex) {
+ // should never occur -> at this point we know the class is present anyway
+ throw new IllegalStateException(ex);
+ }
+ }
+ else {
+ // no importing class was found
+ }
+ }
+ return bean;
+ }
+
+ public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
+ return bean;
+ }
+
+ public int getOrder() {
+ return Ordered.HIGHEST_PRECEDENCE;
+ }
+ }
} | true |
Other | spring-projects | spring-framework | cdb01cbd3795f273b751d0f0a45caa22d07c62da.json | Introduce ImportAware interface
@Configuration classes may implement ImportAware in order to be injected
with the AnnotationMetadata of their @Import'ing class.
Includes the introduction of a new PriorityOrdered
ImportAwareBeanPostProcessor that handles injection of the
importing class metadata. | org.springframework.context/src/main/java/org/springframework/context/annotation/ImportAware.java | @@ -0,0 +1,38 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import org.springframework.beans.factory.Aware;
+import org.springframework.core.type.AnnotationMetadata;
+
+/**
+ * Interface to be implemented by any @{@link Configuration} class that wishes
+ * to be injected with the {@link AnnotationMetadata} of the @{@code Configuration}
+ * class that imported it. Useful in conjunction with annotations that
+ * use @{@link Import} as a meta-annotation.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+public interface ImportAware extends Aware {
+
+ /**
+ * Set the annotation metadata of the importing @{@code Configuration} class.
+ */
+ void setImportMetadata(AnnotationMetadata importMetadata);
+
+} | true |
Other | spring-projects | spring-framework | cdb01cbd3795f273b751d0f0a45caa22d07c62da.json | Introduce ImportAware interface
@Configuration classes may implement ImportAware in order to be injected
with the AnnotationMetadata of their @Import'ing class.
Includes the introduction of a new PriorityOrdered
ImportAwareBeanPostProcessor that handles injection of the
importing class metadata. | org.springframework.context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java | @@ -0,0 +1,137 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.Map;
+
+import org.junit.Test;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.beans.factory.BeanFactoryAware;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
+
+/**
+ * Tests that an ImportAware @Configuration classes gets injected with the
+ * annotation metadata of the @Configuration class that imported it.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ */
+public class ImportAwareTests {
+
+ @Test
+ public void directlyAnnotatedWithImport() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(ImportingConfig.class);
+ ctx.refresh();
+
+ ctx.getBean("importedConfigBean");
+
+ ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class);
+ AnnotationMetadata importMetadata = importAwareConfig.importMetadata;
+ assertThat("import metadata was not injected", importMetadata, notNullValue());
+ assertThat(importMetadata.getClassName(), is(ImportingConfig.class.getName()));
+ Map<String, Object> importAttribs = importMetadata.getAnnotationAttributes(Import.class.getName());
+ Class<?>[] importedClasses = (Class<?>[])importAttribs.get("value");
+ assertThat(importedClasses[0].getName(), is(ImportedConfig.class.getName()));
+ }
+
+ @Test
+ public void indirectlyAnnotatedWithImport() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(IndirectlyImportingConfig.class);
+ ctx.refresh();
+
+ ctx.getBean("importedConfigBean");
+
+ ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class);
+ AnnotationMetadata importMetadata = importAwareConfig.importMetadata;
+ assertThat("import metadata was not injected", importMetadata, notNullValue());
+ assertThat(importMetadata.getClassName(), is(IndirectlyImportingConfig.class.getName()));
+ Map<String, Object> enableAttribs = importMetadata.getAnnotationAttributes(EnableImportedConfig.class.getName());
+ String foo = (String)enableAttribs.get("foo");
+ assertThat(foo, is("xyz"));
+ }
+
+
+ @Configuration
+ @Import(ImportedConfig.class)
+ static class ImportingConfig {
+ }
+
+ @Configuration
+ @EnableImportedConfig(foo="xyz")
+ static class IndirectlyImportingConfig {
+ }
+
+
+ @Target(ElementType.TYPE)
+ @Retention(RetentionPolicy.RUNTIME)
+ @Import(ImportedConfig.class)
+ public @interface EnableImportedConfig {
+ String foo() default "";
+ }
+
+
+ @Configuration
+ static class ImportedConfig implements ImportAware {
+
+ AnnotationMetadata importMetadata;
+
+ public void setImportMetadata(AnnotationMetadata importMetadata) {
+ this.importMetadata = importMetadata;
+ }
+
+ @Bean
+ public BPP importedConfigBean() {
+ return new BPP();
+ }
+
+ @Bean
+ public AsyncAnnotationBeanPostProcessor asyncBPP() {
+ return new AsyncAnnotationBeanPostProcessor();
+ }
+ }
+
+
+ static class BPP implements BeanFactoryAware, BeanPostProcessor {
+
+ public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
+ // TODO Auto-generated method stub
+ return bean;
+ }
+
+ public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
+ // TODO Auto-generated method stub
+ return bean;
+ }
+
+ public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
+ System.out.println("ImportAwareTests.BPP.setBeanFactory()");
+ }
+ }
+} | true |
Other | spring-projects | spring-framework | cdb01cbd3795f273b751d0f0a45caa22d07c62da.json | Introduce ImportAware interface
@Configuration classes may implement ImportAware in order to be injected
with the AnnotationMetadata of their @Import'ing class.
Includes the introduction of a new PriorityOrdered
ImportAwareBeanPostProcessor that handles injection of the
importing class metadata. | org.springframework.context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java | @@ -193,8 +193,8 @@ public void testScopedProxyConfigurationWithClasses() throws Exception {
@Test
public void testScopedConfigurationBeanDefinitionCount() throws Exception {
// count the beans
- // 6 @Beans + 1 Configuration + 2 scoped proxy
- assertEquals(9, ctx.getBeanDefinitionCount());
+ // 6 @Beans + 1 Configuration + 2 scoped proxy + 1 importRegistry
+ assertEquals(10, ctx.getBeanDefinitionCount());
}
// /** | true |
Other | spring-projects | spring-framework | 856da7edb984cd8ad5643a376e536f40e06d8faa.json | Provide dedicated @ComponentScan processing
@ComponentScan is now checked for explicitly and handled immediately
when parsing @Configuration classes. | org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java | @@ -0,0 +1,132 @@
+/*
+ * Copyright 2002-2011 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.context.annotation;
+
+import java.lang.annotation.Annotation;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.support.BeanDefinitionRegistry;
+import org.springframework.beans.factory.support.BeanNameGenerator;
+import org.springframework.context.annotation.ComponentScan.Filter;
+import org.springframework.core.env.Environment;
+import org.springframework.core.io.ResourceLoader;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AnnotationTypeFilter;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.core.type.filter.TypeFilter;
+import org.springframework.util.Assert;
+import org.springframework.util.StringUtils;
+
+/**
+ * Parser for the @{@link ComponentScan} annotation.
+ *
+ * @author Chris Beams
+ * @since 3.1
+ * @see ClassPathBeanDefinitionScanner#scan(String...)
+ * @see ComponentScanBeanDefinitionParser
+ */
+class ComponentScanAnnotationParser {
+
+ private final ResourceLoader resourceLoader;
+ private final Environment environment;
+ private final BeanDefinitionRegistry registry;
+
+ public ComponentScanAnnotationParser(ResourceLoader resourceLoader, Environment environment, BeanDefinitionRegistry registry) {
+ this.resourceLoader = resourceLoader;
+ this.environment = environment;
+ this.registry = registry;
+ }
+
+ public void parse(AnnotationMetadata annotationMetadata) {
+ Map<String, Object> attribs = annotationMetadata.getAnnotationAttributes(ComponentScan.class.getName());
+ if (attribs == null) {
+ // @ComponentScan annotation is not present -> do nothing
+ return;
+ }
+
+ ClassPathBeanDefinitionScanner scanner =
+ new ClassPathBeanDefinitionScanner(registry, (Boolean)attribs.get("useDefaultFilters"));
+
+ Assert.notNull(this.environment, "Environment must not be null");
+ scanner.setEnvironment(this.environment);
+
+ Assert.notNull(this.resourceLoader, "ResourceLoader must not be null");
+ scanner.setResourceLoader(this.resourceLoader);
+
+ scanner.setBeanNameGenerator(BeanUtils.instantiateClass(
+ (Class<?>)attribs.get("nameGenerator"), BeanNameGenerator.class));
+
+ ScopedProxyMode scopedProxyMode = (ScopedProxyMode) attribs.get("scopedProxy");
+ if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
+ scanner.setScopedProxyMode(scopedProxyMode);
+ } else {
+ scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(
+ (Class<?>)attribs.get("scopeResolver"), ScopeMetadataResolver.class));
+ }
+
+ scanner.setResourcePattern((String)attribs.get("resourcePattern"));
+
+ for (Filter filter : (Filter[])attribs.get("includeFilters")) {
+ scanner.addIncludeFilter(createTypeFilter(filter));
+ }
+ for (Filter filter : (Filter[])attribs.get("excludeFilters")) {
+ scanner.addExcludeFilter(createTypeFilter(filter));
+ }
+
+ List<String> basePackages = new ArrayList<String>();
+ for (String pkg : (String[])attribs.get("value")) {
+ if (StringUtils.hasText(pkg)) {
+ basePackages.add(pkg);
+ }
+ }
+ for (String pkg : (String[])attribs.get("basePackages")) {
+ if (StringUtils.hasText(pkg)) {
+ basePackages.add(pkg);
+ }
+ }
+ for (Class<?> clazz : (Class<?>[])attribs.get("basePackageClasses")) {
+ // TODO: loading user types directly here. implications on load-time
+ // weaving may mean we need to revert to stringified class names in
+ // annotation metadata
+ basePackages.add(clazz.getPackage().getName());
+ }
+
+ if (basePackages.isEmpty()) {
+ throw new IllegalStateException("At least one base package must be specified");
+ }
+
+ scanner.scan(basePackages.toArray(new String[]{}));
+ }
+
+ private TypeFilter createTypeFilter(Filter filter) {
+ switch (filter.type()) {
+ case ANNOTATION:
+ @SuppressWarnings("unchecked")
+ Class<Annotation> filterClass = (Class<Annotation>)filter.value();
+ return new AnnotationTypeFilter(filterClass);
+ case ASSIGNABLE_TYPE:
+ return new AssignableTypeFilter(filter.value());
+ case CUSTOM:
+ return BeanUtils.instantiateClass(filter.value(), TypeFilter.class);
+ default:
+ throw new IllegalArgumentException("unknown filter type " + filter.type());
+ }
+ }
+} | true |
Other | spring-projects | spring-framework | 856da7edb984cd8ad5643a376e536f40e06d8faa.json | Provide dedicated @ComponentScan processing
@ComponentScan is now checked for explicitly and handled immediately
when parsing @Configuration classes. | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java | @@ -95,6 +95,8 @@ public class ConfigurationClassBeanDefinitionReader {
private Environment environment;
+ private final ComponentScanAnnotationParser componentScanParser;
+
/**
* Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
* to populate the given {@link BeanDefinitionRegistry}.
@@ -111,6 +113,8 @@ public ConfigurationClassBeanDefinitionReader(final BeanDefinitionRegistry regis
this.metadataReaderFactory = metadataReaderFactory;
this.resourceLoader = resourceLoader;
this.environment = environment;
+
+ this.componentScanParser = new ComponentScanAnnotationParser(resourceLoader, environment, registry);
}
@@ -130,6 +134,7 @@ public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
*/
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
AnnotationMetadata metadata = configClass.getMetadata();
+ componentScanParser.parse(metadata);
doLoadBeanDefinitionForConfigurationClassIfNecessary(configClass);
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
loadBeanDefinitionsForBeanMethod(beanMethod); | true |
Other | spring-projects | spring-framework | 856da7edb984cd8ad5643a376e536f40e06d8faa.json | Provide dedicated @ComponentScan processing
@ComponentScan is now checked for explicitly and handled immediately
when parsing @Configuration classes. | org.springframework.context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java | @@ -34,7 +34,6 @@
import org.springframework.beans.factory.annotation.CustomAutowireConfigurer;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.SimpleMapScope;
-import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ComponentScan.Filter;
@@ -114,7 +113,7 @@ public void invalidComponentScanDeclaration_noPackagesSpecified() {
try {
ctx.refresh();
fail("Expected exception when parsing @ComponentScan definition that declares no packages");
- } catch (BeanDefinitionParsingException ex) {
+ } catch (IllegalStateException ex) {
assertThat(ex.getMessage(), containsString("At least one base package must be specified"));
}
} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | build-spring-framework/resources/changelog.txt | @@ -7,6 +7,8 @@ Changes in version 3.1 M2 (2011-??-??)
--------------------------------------
* deprecated AbstractJUnit38SpringContextTests and AbstractTransactionalJUnit38SpringContextTests
+* eliminated @Feature support in favor of @Enable* and framework-provided @Configuration classes
+* introduced @EnableTransactionManagement, @EnableScheduling, and other @Enable* annotations
Changes in version 3.1 M1 (2011-02-11) | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.aop/src/main/java/org/springframework/aop/config/AopNamespaceUtils.java | @@ -16,13 +16,12 @@
package org.springframework.aop.config;
+import org.w3c.dom.Element;
+
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
-import org.springframework.beans.factory.parsing.ComponentRegistrar;
-import org.springframework.beans.factory.parsing.ComponentRegistrarAdapter;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ParserContext;
-import org.w3c.dom.Element;
/**
* Utility class for handling registration of auto-proxy creators used internally
@@ -53,41 +52,22 @@ public abstract class AopNamespaceUtils {
private static final String EXPOSE_PROXY_ATTRIBUTE = "expose-proxy";
- /**
- * @deprecated since Spring 3.1 in favor of
- * {@link #registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry, ComponentRegistrar, Object, Boolean, Boolean)}
- */
- @Deprecated
public static void registerAutoProxyCreatorIfNecessary(
ParserContext parserContext, Element sourceElement) {
BeanDefinition beanDefinition = AopConfigUtils.registerAutoProxyCreatorIfNecessary(
parserContext.getRegistry(), parserContext.extractSource(sourceElement));
useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
- registerComponentIfNecessary(beanDefinition, new ComponentRegistrarAdapter(parserContext));
- }
-
- public static void registerAutoProxyCreatorIfNecessary(
- BeanDefinitionRegistry registry, ComponentRegistrar parserContext, Object source, Boolean proxyTargetClass, Boolean exposeProxy) {
-
- BeanDefinition beanDefinition =
- AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry, source);
- useClassProxyingIfNecessary(registry, proxyTargetClass, exposeProxy);
registerComponentIfNecessary(beanDefinition, parserContext);
}
- public static void registerAutoProxyCreatorIfNecessary(
- BeanDefinitionRegistry registry, ComponentRegistrar parserContext, Object source, Boolean proxyTargetClass) {
- registerAutoProxyCreatorIfNecessary(registry, parserContext, source, proxyTargetClass, false);
- }
-
public static void registerAspectJAutoProxyCreatorIfNecessary(
ParserContext parserContext, Element sourceElement) {
BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAutoProxyCreatorIfNecessary(
parserContext.getRegistry(), parserContext.extractSource(sourceElement));
useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
- registerComponentIfNecessary(beanDefinition, new ComponentRegistrarAdapter(parserContext));
+ registerComponentIfNecessary(beanDefinition, parserContext);
}
public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
@@ -96,7 +76,7 @@ public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
parserContext.getRegistry(), parserContext.extractSource(sourceElement));
useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
- registerComponentIfNecessary(beanDefinition, new ComponentRegistrarAdapter(parserContext));
+ registerComponentIfNecessary(beanDefinition, parserContext);
}
/**
@@ -108,7 +88,7 @@ public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
public static void registerAutoProxyCreatorIfNecessary(ParserContext parserContext, Object source) {
BeanDefinition beanDefinition = AopConfigUtils.registerAutoProxyCreatorIfNecessary(
parserContext.getRegistry(), source);
- registerComponentIfNecessary(beanDefinition, new ComponentRegistrarAdapter(parserContext));
+ registerComponentIfNecessary(beanDefinition, parserContext);
}
/**
@@ -121,12 +101,6 @@ public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistr
}
- /**
- * @deprecated since Spring 3.1 in favor of
- * {@link #useClassProxyingIfNecessary(BeanDefinitionRegistry, Boolean, Boolean)}
- * which does not require a parameter of type org.w3c.dom.Element
- */
- @Deprecated
private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, Element sourceElement) {
if (sourceElement != null) {
boolean proxyTargetClass = Boolean.valueOf(sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE));
@@ -140,20 +114,11 @@ private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry,
}
}
- private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, Boolean proxyTargetClass, Boolean exposeProxy) {
- if (proxyTargetClass) {
- AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
- }
- if (exposeProxy) {
- AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
- }
- }
-
- private static void registerComponentIfNecessary(BeanDefinition beanDefinition, ComponentRegistrar componentRegistrar) {
+ private static void registerComponentIfNecessary(BeanDefinition beanDefinition, ParserContext parserContext) {
if (beanDefinition != null) {
BeanComponentDefinition componentDefinition =
new BeanComponentDefinition(beanDefinition, AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
- componentRegistrar.registerComponent(componentDefinition);
+ parserContext.registerComponent(componentDefinition);
}
}
| true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ComponentRegistrar.java | @@ -1,35 +0,0 @@
-/*
- * Copyright 2002-2011 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.beans.factory.parsing;
-
-import org.springframework.beans.factory.config.BeanDefinition;
-
-/**
- * TODO SPR-7420: document
- *
- * @author Chris Beams
- * @since 3.1
- */
-public interface ComponentRegistrar {
-
- String registerWithGeneratedName(BeanDefinition beanDefinition);
-
- void registerBeanComponent(BeanComponentDefinition component);
-
- void registerComponent(ComponentDefinition component);
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ComponentRegistrarAdapter.java | @@ -1,55 +0,0 @@
-/*
- * Copyright 2002-2011 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.beans.factory.parsing;
-
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.beans.factory.xml.ParserContext;
-
-/**
- * TODO SPR-7420: document
- * <p>Adapter is necessary as opposed to having ParserContext
- * implement ComponentRegistrar directly due to tooling issues.
- * STS may ship with a version of Spring older that 3.1 (when
- * this type was introduced), and will run into
- * IncompatibleClassChangeErrors when it's (3.0.5) ParserContext
- * tries to mix with our (3.1.0) BeanDefinitionParser
- * (and related) infrastructure.
- *
- * @author Chris Beams
- * @since 3.1
- */
-public class ComponentRegistrarAdapter implements ComponentRegistrar {
-
- private final ParserContext parserContext;
-
- public ComponentRegistrarAdapter(ParserContext parserContext) {
- this.parserContext = parserContext;
- }
-
- public String registerWithGeneratedName(BeanDefinition beanDefinition) {
- return this.parserContext.getReaderContext().registerWithGeneratedName(beanDefinition);
- }
-
- public void registerBeanComponent(BeanComponentDefinition component) {
- this.parserContext.registerBeanComponent(component);
- }
-
- public void registerComponent(ComponentDefinition component) {
- this.parserContext.registerComponent(component);
- }
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ProblemCollector.java | @@ -1,35 +0,0 @@
-/*
- * Copyright 2002-2011 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.beans.factory.parsing;
-
-/**
- * TODO SPR-7420: document
- *
- * @author Chris Beams
- * @since 3.1
- */
-public interface ProblemCollector {
-
- void error(String message);
-
- void error(String message, Throwable cause);
-
- void reportProblems(ProblemReporter reporter);
-
- boolean hasErrors();
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/SimpleProblemCollector.java | @@ -1,59 +0,0 @@
-/*
- * Copyright 2002-2011 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.beans.factory.parsing;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.core.io.DescriptiveResource;
-
-/**
- * TODO SPR-7420: document
- *
- * @author Chris Beams
- * @since 3.1
- */
-public class SimpleProblemCollector implements ProblemCollector {
-
- private Location location = null;
- private List<Problem> errors = new ArrayList<Problem>();
-
- public SimpleProblemCollector(Object location) {
- if (location != null) {
- this.location = new Location(new DescriptiveResource(location.toString()));
- }
- }
-
- public void error(String message) {
- this.errors.add(new Problem(message, this.location));
- }
-
- public void error(String message, Throwable cause) {
- this.errors.add(new Problem(message, this.location, null, cause));
- }
-
- public void reportProblems(ProblemReporter reporter) {
- for (Problem error : errors) {
- reporter.error(error);
- }
- }
-
- public boolean hasErrors() {
- return this.errors.size() > 0;
- }
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParser.java | @@ -22,27 +22,18 @@
/**
* Interface used by the {@link DefaultBeanDefinitionDocumentReader} to handle custom,
- * top-level (directly under {@code <beans>}) tags.
+ * top-level (directly under {@code <beans/>}) tags.
*
* <p>Implementations are free to turn the metadata in the custom tag into as many
* {@link BeanDefinition BeanDefinitions} as required.
*
* <p>The parser locates a {@link BeanDefinitionParser} from the associated
* {@link NamespaceHandler} for the namespace in which the custom tag resides.
*
- * <p>Implementations are encouraged to decouple XML parsing from bean registration by
- * parsing element(s) into a {@link org.springframework.context.FeatureSpecification
- * FeatureSpecification} object and subsequently executing that specification.
- * Doing so allows for maximum reuse between XML-based and annotation-based
- * configuration options.
- *
* @author Rob Harrop
* @since 2.0
* @see NamespaceHandler
* @see AbstractBeanDefinitionParser
- * @see org.springframework.beans.factory.xml.BeanDefinitionDecorator
- * @see org.springframework.context.FeatureSpecification
- * @see org.springframework.context.AbstractSpecificationExecutor
*/
public interface BeanDefinitionParser {
@@ -53,12 +44,11 @@ public interface BeanDefinitionParser {
* embedded in the supplied {@link ParserContext}.
* <p>Implementations must return the primary {@link BeanDefinition} that results
* from the parse if they will ever be used in a nested fashion (for example as
- * an inner tag in a <code><property/></code> tag). Implementations may return
- * <code>null</code> if they will <strong>not</strong> be used in a nested fashion.
+ * an inner tag in a {@code <property/>} tag). Implementations may return
+ * {@code null} if they will <strong>not</strong> be used in a nested fashion.
* @param element the element that is to be parsed into one or more {@link BeanDefinition BeanDefinitions}
* @param parserContext the object encapsulating the current state of the parsing process;
- * provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry
- * BeanDefinitionRegistry}.
+ * provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}
* @return the primary {@link BeanDefinition}
*/
BeanDefinition parse(Element element, ParserContext parserContext); | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/.springBeans | @@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
- <pluginVersion><![CDATA[2.5.0.201008272200-CI-R3822-B852]]></pluginVersion>
+ <pluginVersion><![CDATA[2.6.0.201103160035-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
@@ -11,7 +11,6 @@
<config>src/test/java/org/springframework/context/annotation/configuration/SecondLevelSubConfig-context.xml</config>
<config>src/test/java/org/springframework/context/annotation/configuration/ImportXmlWithAopNamespace-context.xml</config>
<config>src/test/java/org/springframework/context/annotation/Spr6602Tests-context.xml</config>
- <config>src/test/java/org/springframework/context/annotation/FeatureConfigurationImportResourceTests-context.xml</config>
</configs>
<configSets>
</configSets> | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/src/main/java/org/springframework/context/annotation/BeanMethod.java | @@ -16,13 +16,13 @@
package org.springframework.context.annotation;
-import org.springframework.beans.factory.parsing.Location;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.beans.factory.parsing.ProblemReporter;
import org.springframework.core.type.MethodMetadata;
/**
- * Represents a {@link Configuration} class method marked with the {@link Bean} annotation.
+ * Represents a {@link Configuration} class method marked with the
+ * {@link Bean} annotation.
*
* @author Chris Beams
* @author Juergen Hoeller
@@ -31,30 +31,13 @@
* @see ConfigurationClassParser
* @see ConfigurationClassBeanDefinitionReader
*/
-final class BeanMethod {
-
- private final MethodMetadata metadata;
-
- private final ConfigurationClass configurationClass;
-
+final class BeanMethod extends ConfigurationMethod {
public BeanMethod(MethodMetadata metadata, ConfigurationClass configurationClass) {
- this.metadata = metadata;
- this.configurationClass = configurationClass;
- }
-
- public MethodMetadata getMetadata() {
- return this.metadata;
- }
-
- public ConfigurationClass getConfigurationClass() {
- return this.configurationClass;
- }
-
- public Location getResourceLocation() {
- return new Location(this.configurationClass.getResource(), this.metadata);
+ super(metadata, configurationClass);
}
+ @Override
public void validate(ProblemReporter problemReporter) {
if (this.configurationClass.getMetadata().isAnnotated(Configuration.class.getName())) {
if (!getMetadata().isOverridable()) {
@@ -68,13 +51,6 @@ public void validate(ProblemReporter problemReporter) {
}
}
- @Override
- public String toString() {
- return String.format("[%s:name=%s,declaringClass=%s]",
- this.getClass().getSimpleName(), this.getMetadata().getMethodName(), this.getMetadata().getDeclaringClassName());
- }
-
-
/**
* {@link Bean} methods must be overridable in order to accommodate CGLIB.
*/ | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java | @@ -1,97 +0,0 @@
-/*
- * Copyright 2002-2011 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.context.annotation;
-
-import java.util.Map;
-
-import org.springframework.context.annotation.ComponentScan.Filter;
-import org.springframework.core.annotation.AnnotationUtils;
-import org.springframework.core.type.AnnotationMetadata;
-import org.springframework.util.Assert;
-import org.springframework.util.ClassUtils;
-
-/**
- * {@link FeatureAnnotationParser} implementation that reads attributes from a
- * {@link ComponentScan @ComponentScan} annotation into a {@link ComponentScanSpec}
- * which can in turn be executed by {@link ComponentScanExecutor}.
- * {@link ComponentScanBeanDefinitionParser} serves the same role for
- * the {@code <context:component-scan>} XML element.
- *
- * <p>Note that {@link ComponentScanSpec} objects may be directly
- * instantiated and returned from {@link Feature @Feature} methods as an
- * alternative to using the {@link ComponentScan @ComponentScan} annotation.
- *
- * @author Chris Beams
- * @since 3.1
- * @see ComponentScan
- * @see ComponentScanSpec
- * @see ComponentScanExecutor
- * @see ComponentScanBeanDefinitionParser
- * @see ConfigurationClassBeanDefinitionReader
- */
-final class ComponentScanAnnotationParser implements FeatureAnnotationParser {
-
- /**
- * Create and return a new {@link ComponentScanSpec} from the given
- * {@link ComponentScan} annotation metadata.
- * @throws IllegalArgumentException if ComponentScan attributes are not present in metadata
- */
- public ComponentScanSpec process(AnnotationMetadata metadata) {
- Map<String, Object> attribs = metadata.getAnnotationAttributes(ComponentScan.class.getName(), true);
- Assert.notNull(attribs, String.format("@ComponentScan annotation not found " +
- "while parsing metadata for class [%s].", metadata.getClassName()));
-
- ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
- ComponentScanSpec spec = new ComponentScanSpec();
-
- for (String pkg : (String[])attribs.get("value")) {
- spec.addBasePackage(pkg);
- }
- for (String pkg : (String[])attribs.get("basePackages")) {
- spec.addBasePackage(pkg);
- }
- for (String className : (String[])attribs.get("basePackageClasses")) {
- spec.addBasePackage(className.substring(0, className.lastIndexOf('.')));
- }
-
- String resolverAttribute = "scopeResolver";
- if (!((String)attribs.get(resolverAttribute)).equals(((Class<?>)AnnotationUtils.getDefaultValue(ComponentScan.class, resolverAttribute)).getName())) {
- spec.scopeMetadataResolver((String)attribs.get(resolverAttribute), classLoader);
- }
- String scopedProxyAttribute = "scopedProxy";
- ScopedProxyMode scopedProxyMode = (ScopedProxyMode) attribs.get(scopedProxyAttribute);
- if (scopedProxyMode != ((ScopedProxyMode)AnnotationUtils.getDefaultValue(ComponentScan.class, scopedProxyAttribute))) {
- spec.scopedProxyMode(scopedProxyMode);
- }
-
- for (Filter filter : (Filter[]) attribs.get("includeFilters")) {
- spec.addIncludeFilter(filter.type().toString(), filter.value().getName(), classLoader);
- }
- for (Filter filter : (Filter[]) attribs.get("excludeFilters")) {
- spec.addExcludeFilter(filter.type().toString(), filter.value().getName(), classLoader);
- }
-
- spec.resourcePattern((String)attribs.get("resourcePattern"))
- .useDefaultFilters((Boolean)attribs.get("useDefaultFilters"))
- .beanNameGenerator((String)attribs.get("nameGenerator"), classLoader)
- .source(metadata.getClassName())
- .sourceName(metadata.getClassName());
-
- return spec;
- }
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2009 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,60 +16,263 @@
package org.springframework.context.annotation;
-import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.context.config.AbstractSpecificationBeanDefinitionParser;
-import org.springframework.context.config.FeatureSpecification;
+import java.lang.annotation.Annotation;
+import java.util.Set;
+import java.util.regex.Pattern;
+
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.FatalBeanException;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinitionHolder;
+import org.springframework.beans.factory.parsing.BeanComponentDefinition;
+import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
+import org.springframework.beans.factory.support.BeanNameGenerator;
+import org.springframework.beans.factory.xml.BeanDefinitionParser;
+import org.springframework.beans.factory.xml.ParserContext;
+import org.springframework.beans.factory.xml.XmlReaderContext;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.type.filter.AnnotationTypeFilter;
+import org.springframework.core.type.filter.AspectJTypeFilter;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.core.type.filter.RegexPatternTypeFilter;
+import org.springframework.core.type.filter.TypeFilter;
+import org.springframework.util.StringUtils;
+
/**
- * Parser for the {@code <context:component-scan/>} element. Parsed metadata is
- * used to populate and execute a {@link ComponentScanSpec} instance.
+ * Parser for the {@code <context:component-scan/>} element.
*
* @author Mark Fisher
* @author Ramnivas Laddad
* @author Juergen Hoeller
- * @author Chris Beams
* @since 2.5
- * @see ComponentScan
- * @see ComponentScanSpec
- * @see ComponentScanExecutor
*/
-public class ComponentScanBeanDefinitionParser extends AbstractSpecificationBeanDefinitionParser {
-
- public FeatureSpecification doParse(Element element, ParserContext parserContext) {
- ClassLoader classLoader = parserContext.getReaderContext().getResourceLoader().getClassLoader();
-
- ComponentScanSpec spec =
- ComponentScanSpec.forDelimitedPackages(element.getAttribute("base-package"))
- .includeAnnotationConfig(element.getAttribute("annotation-config"))
- .useDefaultFilters(element.getAttribute("use-default-filters"))
- .resourcePattern(element.getAttribute("resource-pattern"))
- .beanNameGenerator(element.getAttribute("name-generator"), classLoader)
- .scopeMetadataResolver(element.getAttribute("scope-resolver"), classLoader)
- .scopedProxyMode(element.getAttribute("scoped-proxy"))
- .beanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults())
- .autowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns());
+public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
+
+ private static final String BASE_PACKAGE_ATTRIBUTE = "base-package";
+
+ private static final String RESOURCE_PATTERN_ATTRIBUTE = "resource-pattern";
+
+ private static final String USE_DEFAULT_FILTERS_ATTRIBUTE = "use-default-filters";
+
+ private static final String ANNOTATION_CONFIG_ATTRIBUTE = "annotation-config";
+
+ private static final String NAME_GENERATOR_ATTRIBUTE = "name-generator";
+
+ private static final String SCOPE_RESOLVER_ATTRIBUTE = "scope-resolver";
+
+ private static final String SCOPED_PROXY_ATTRIBUTE = "scoped-proxy";
+
+ private static final String EXCLUDE_FILTER_ELEMENT = "exclude-filter";
+
+ private static final String INCLUDE_FILTER_ELEMENT = "include-filter";
+
+ private static final String FILTER_TYPE_ATTRIBUTE = "type";
+
+ private static final String FILTER_EXPRESSION_ATTRIBUTE = "expression";
+
+
+ public BeanDefinition parse(Element element, ParserContext parserContext) {
+ String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE),
+ ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
+
+ // Actually scan for bean definitions and register them.
+ ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
+ Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
+ registerComponents(parserContext.getReaderContext(), beanDefinitions, element);
+
+ return null;
+ }
+
+ protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
+ XmlReaderContext readerContext = parserContext.getReaderContext();
+
+ boolean useDefaultFilters = true;
+ if (element.hasAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE)) {
+ useDefaultFilters = Boolean.valueOf(element.getAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE));
+ }
+
+ // Delegate bean definition registration to scanner class.
+ ClassPathBeanDefinitionScanner scanner = createScanner(readerContext, useDefaultFilters);
+ scanner.setResourceLoader(readerContext.getResourceLoader());
+ scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults());
+ scanner.setAutowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns());
+
+ if (element.hasAttribute(RESOURCE_PATTERN_ATTRIBUTE)) {
+ scanner.setResourcePattern(element.getAttribute(RESOURCE_PATTERN_ATTRIBUTE));
+ }
+
+ try {
+ parseBeanNameGenerator(element, scanner);
+ }
+ catch (Exception ex) {
+ readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
+ }
+
+ try {
+ parseScope(element, scanner);
+ }
+ catch (Exception ex) {
+ readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
+ }
+
+ parseTypeFilters(element, scanner, readerContext, parserContext);
+
+ return scanner;
+ }
+
+ protected ClassPathBeanDefinitionScanner createScanner(XmlReaderContext readerContext, boolean useDefaultFilters) {
+ return new ClassPathBeanDefinitionScanner(readerContext.getRegistry(), useDefaultFilters);
+ }
+
+ protected void registerComponents(
+ XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {
+
+ Object source = readerContext.extractSource(element);
+ CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);
+
+ for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
+ compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
+ }
+
+ // Register annotation config processors, if necessary.
+ boolean annotationConfig = true;
+ if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
+ annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
+ }
+ if (annotationConfig) {
+ Set<BeanDefinitionHolder> processorDefinitions =
+ AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
+ for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
+ compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
+ }
+ }
+
+ readerContext.fireComponentRegistered(compositeDef);
+ }
+
+ protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
+ if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
+ BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
+ element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
+ scanner.getResourceLoader().getClassLoader());
+ scanner.setBeanNameGenerator(beanNameGenerator);
+ }
+ }
+
+ protected void parseScope(Element element, ClassPathBeanDefinitionScanner scanner) {
+ // Register ScopeMetadataResolver if class name provided.
+ if (element.hasAttribute(SCOPE_RESOLVER_ATTRIBUTE)) {
+ if (element.hasAttribute(SCOPED_PROXY_ATTRIBUTE)) {
+ throw new IllegalArgumentException(
+ "Cannot define both 'scope-resolver' and 'scoped-proxy' on <component-scan> tag");
+ }
+ ScopeMetadataResolver scopeMetadataResolver = (ScopeMetadataResolver) instantiateUserDefinedStrategy(
+ element.getAttribute(SCOPE_RESOLVER_ATTRIBUTE), ScopeMetadataResolver.class,
+ scanner.getResourceLoader().getClassLoader());
+ scanner.setScopeMetadataResolver(scopeMetadataResolver);
+ }
+
+ if (element.hasAttribute(SCOPED_PROXY_ATTRIBUTE)) {
+ String mode = element.getAttribute(SCOPED_PROXY_ATTRIBUTE);
+ if ("targetClass".equals(mode)) {
+ scanner.setScopedProxyMode(ScopedProxyMode.TARGET_CLASS);
+ }
+ else if ("interfaces".equals(mode)) {
+ scanner.setScopedProxyMode(ScopedProxyMode.INTERFACES);
+ }
+ else if ("no".equals(mode)) {
+ scanner.setScopedProxyMode(ScopedProxyMode.NO);
+ }
+ else {
+ throw new IllegalArgumentException("scoped-proxy only supports 'no', 'interfaces' and 'targetClass'");
+ }
+ }
+ }
+
+ protected void parseTypeFilters(
+ Element element, ClassPathBeanDefinitionScanner scanner, XmlReaderContext readerContext, ParserContext parserContext) {
// Parse exclude and include filter elements.
+ ClassLoader classLoader = scanner.getResourceLoader().getClassLoader();
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String localName = parserContext.getDelegate().getLocalName(node);
- String filterType = ((Element)node).getAttribute("type");
- String expression = ((Element)node).getAttribute("expression");
- if ("include-filter".equals(localName)) {
- spec.addIncludeFilter(filterType, expression, classLoader);
+ try {
+ if (INCLUDE_FILTER_ELEMENT.equals(localName)) {
+ TypeFilter typeFilter = createTypeFilter((Element) node, classLoader);
+ scanner.addIncludeFilter(typeFilter);
+ }
+ else if (EXCLUDE_FILTER_ELEMENT.equals(localName)) {
+ TypeFilter typeFilter = createTypeFilter((Element) node, classLoader);
+ scanner.addExcludeFilter(typeFilter);
+ }
}
- else if ("exclude-filter".equals(localName)) {
- spec.addExcludeFilter(filterType, expression, classLoader);
+ catch (Exception ex) {
+ readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
}
}
}
+ }
- return spec;
+ @SuppressWarnings("unchecked")
+ protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) {
+ String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
+ String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
+ try {
+ if ("annotation".equals(filterType)) {
+ return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression));
+ }
+ else if ("assignable".equals(filterType)) {
+ return new AssignableTypeFilter(classLoader.loadClass(expression));
+ }
+ else if ("aspectj".equals(filterType)) {
+ return new AspectJTypeFilter(expression, classLoader);
+ }
+ else if ("regex".equals(filterType)) {
+ return new RegexPatternTypeFilter(Pattern.compile(expression));
+ }
+ else if ("custom".equals(filterType)) {
+ Class filterClass = classLoader.loadClass(expression);
+ if (!TypeFilter.class.isAssignableFrom(filterClass)) {
+ throw new IllegalArgumentException(
+ "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
+ }
+ return (TypeFilter) BeanUtils.instantiateClass(filterClass);
+ }
+ else {
+ throw new IllegalArgumentException("Unsupported filter type: " + filterType);
+ }
+ }
+ catch (ClassNotFoundException ex) {
+ throw new FatalBeanException("Type filter class not found: " + expression, ex);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private Object instantiateUserDefinedStrategy(String className, Class strategyType, ClassLoader classLoader) {
+ Object result = null;
+ try {
+ result = classLoader.loadClass(className).newInstance();
+ }
+ catch (ClassNotFoundException ex) {
+ throw new IllegalArgumentException("Class [" + className + "] for strategy [" +
+ strategyType.getName() + "] not found", ex);
+ }
+ catch (Exception ex) {
+ throw new IllegalArgumentException("Unable to instantiate class [" + className + "] for strategy [" +
+ strategyType.getName() + "]. A zero-argument constructor is required", ex);
+ }
+
+ if (!strategyType.isAssignableFrom(result.getClass())) {
+ throw new IllegalArgumentException("Provided class name must be an implementation of " + strategyType);
+ }
+ return result;
}
} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanExecutor.java | @@ -1,110 +0,0 @@
-/*
- * Copyright 2002-2011 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.context.annotation;
-
-import java.util.Set;
-
-import org.springframework.beans.factory.config.BeanDefinitionHolder;
-import org.springframework.beans.factory.parsing.BeanComponentDefinition;
-import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
-import org.springframework.beans.factory.support.BeanDefinitionRegistry;
-import org.springframework.context.config.AbstractSpecificationExecutor;
-import org.springframework.context.config.SpecificationContext;
-import org.springframework.core.env.Environment;
-import org.springframework.core.io.ResourceLoader;
-import org.springframework.core.type.filter.TypeFilter;
-
-/**
- * Executes the {@link ComponentScanSpec} feature specification.
- *
- * @author Chris Beams
- * @since 3.1
- * @see ComponentScanSpec
- * @see ComponentScanBeanDefinitionParser
- * @see ComponentScan
- */
-final class ComponentScanExecutor extends AbstractSpecificationExecutor<ComponentScanSpec> {
-
- /**
- * Configure a {@link ClassPathBeanDefinitionScanner} based on the content of
- * the given specification and perform actual scanning and bean definition
- * registration.
- */
- protected void doExecute(ComponentScanSpec spec, SpecificationContext specificationContext) {
- BeanDefinitionRegistry registry = specificationContext.getRegistry();
- ResourceLoader resourceLoader = specificationContext.getResourceLoader();
- Environment environment = specificationContext.getEnvironment();
-
- ClassPathBeanDefinitionScanner scanner = spec.useDefaultFilters() == null ?
- new ClassPathBeanDefinitionScanner(registry) :
- new ClassPathBeanDefinitionScanner(registry, spec.useDefaultFilters());
-
- scanner.setResourceLoader(resourceLoader);
- scanner.setEnvironment(environment);
-
- if (spec.beanDefinitionDefaults() != null) {
- scanner.setBeanDefinitionDefaults(spec.beanDefinitionDefaults());
- }
- if (spec.autowireCandidatePatterns() != null) {
- scanner.setAutowireCandidatePatterns(spec.autowireCandidatePatterns());
- }
-
- if (spec.resourcePattern() != null) {
- scanner.setResourcePattern(spec.resourcePattern());
- }
- if (spec.beanNameGenerator() != null) {
- scanner.setBeanNameGenerator(spec.beanNameGenerator());
- }
- if (spec.includeAnnotationConfig() != null) {
- scanner.setIncludeAnnotationConfig(spec.includeAnnotationConfig());
- }
- if (spec.scopeMetadataResolver() != null) {
- scanner.setScopeMetadataResolver(spec.scopeMetadataResolver());
- }
- if (spec.scopedProxyMode() != null) {
- scanner.setScopedProxyMode(spec.scopedProxyMode());
- }
- for (TypeFilter filter : spec.includeFilters()) {
- scanner.addIncludeFilter(filter);
- }
- for (TypeFilter filter : spec.excludeFilters()) {
- scanner.addExcludeFilter(filter);
- }
-
- Set<BeanDefinitionHolder> scannedBeans = scanner.doScan(spec.basePackages());
-
- Object source = spec.source();
- String sourceName = spec.sourceName();
- CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(sourceName, source);
-
- for (BeanDefinitionHolder beanDefHolder : scannedBeans) {
- compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
- }
-
- // Register annotation config processors, if necessary.
- if ((spec.includeAnnotationConfig() != null) && spec.includeAnnotationConfig()) {
- Set<BeanDefinitionHolder> processorDefinitions =
- AnnotationConfigUtils.registerAnnotationConfigProcessors(registry, source);
- for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
- compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
- }
- }
-
- specificationContext.getRegistrar().registerComponent(compositeDef);
- }
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanSpec.java | @@ -1,460 +0,0 @@
-/*
- * Copyright 2002-2011 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.context.annotation;
-
-import java.io.IOException;
-import java.lang.annotation.Annotation;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import org.springframework.beans.BeanUtils;
-import org.springframework.beans.factory.parsing.ProblemCollector;
-import org.springframework.beans.factory.support.BeanDefinitionDefaults;
-import org.springframework.beans.factory.support.BeanNameGenerator;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.config.AbstractFeatureSpecification;
-import org.springframework.context.config.FeatureSpecificationExecutor;
-import org.springframework.core.type.classreading.MetadataReader;
-import org.springframework.core.type.classreading.MetadataReaderFactory;
-import org.springframework.core.type.filter.AnnotationTypeFilter;
-import org.springframework.core.type.filter.AspectJTypeFilter;
-import org.springframework.core.type.filter.AssignableTypeFilter;
-import org.springframework.core.type.filter.RegexPatternTypeFilter;
-import org.springframework.core.type.filter.TypeFilter;
-import org.springframework.util.Assert;
-import org.springframework.util.StringUtils;
-
-/**
- * Specifies the configuration of Spring's <em>component-scanning</em> feature.
- * May be used directly within a {@link Feature @Feature} method, or indirectly
- * through the {@link ComponentScan @ComponentScan} annotation.
- *
- * @author Chris Beams
- * @since 3.1
- * @see ComponentScan
- * @see ComponentScanAnnotationParser
- * @see ComponentScanBeanDefinitionParser
- * @see ComponentScanExecutor
- */
-public final class ComponentScanSpec extends AbstractFeatureSpecification {
-
- private static final Class<? extends FeatureSpecificationExecutor> EXECUTOR_TYPE = ComponentScanExecutor.class;
-
- private Boolean includeAnnotationConfig = null;
- private String resourcePattern = null;
- private List<String> basePackages = new ArrayList<String>();
- private Object beanNameGenerator = null;
- private Object scopeMetadataResolver = null;
- private Object scopedProxyMode = null;
- private Boolean useDefaultFilters = null;
- private List<Object> includeFilters = new ArrayList<Object>();
- private List<Object> excludeFilters = new ArrayList<Object>();
-
- private BeanDefinitionDefaults beanDefinitionDefaults;
- private String[] autowireCandidatePatterns;
-
- private ClassLoader classLoader;
-
- /**
- * Package-visible constructor for use by {@link ComponentScanBeanDefinitionParser}.
- * End users should always call String... or Class<?>... constructors to specify
- * base packages.
- *
- * @see #validate()
- */
- ComponentScanSpec() {
- super(EXECUTOR_TYPE);
- }
-
- /**
- *
- * @param basePackages
- * @see #forDelimitedPackages(String)
- */
- public ComponentScanSpec(String... basePackages) {
- this();
- Assert.notEmpty(basePackages, "At least one base package must be specified");
- for (String basePackage : basePackages) {
- addBasePackage(basePackage);
- }
- }
-
- public ComponentScanSpec(Class<?>... basePackageClasses) {
- this(packagesFor(basePackageClasses));
- }
-
-
- public ComponentScanSpec includeAnnotationConfig(Boolean includeAnnotationConfig) {
- this.includeAnnotationConfig = includeAnnotationConfig;
- return this;
- }
-
- ComponentScanSpec includeAnnotationConfig(String includeAnnotationConfig) {
- if (StringUtils.hasText(includeAnnotationConfig)) {
- this.includeAnnotationConfig = Boolean.valueOf(includeAnnotationConfig);
- }
- return this;
- }
-
- Boolean includeAnnotationConfig() {
- return this.includeAnnotationConfig;
- }
-
- public ComponentScanSpec resourcePattern(String resourcePattern) {
- if (StringUtils.hasText(resourcePattern)) {
- this.resourcePattern = resourcePattern;
- }
- return this;
- }
-
- String resourcePattern() {
- return resourcePattern;
- }
-
- ComponentScanSpec addBasePackage(String basePackage) {
- if (StringUtils.hasText(basePackage)) {
- this.basePackages.add(basePackage);
- }
- return this;
- }
-
- /**
- * Return the set of base packages specified, never {@code null}, never empty
- * post-validation.
- * @see #doValidate(SimpleProblemReporter)
- */
- String[] basePackages() {
- return this.basePackages.toArray(new String[this.basePackages.size()]);
- }
-
- public ComponentScanSpec beanNameGenerator(BeanNameGenerator beanNameGenerator) {
- this.beanNameGenerator = beanNameGenerator;
- return this;
- }
-
- /**
- * Set the class name of the BeanNameGenerator to be used and the ClassLoader
- * to load it.
- */
- ComponentScanSpec beanNameGenerator(String beanNameGenerator, ClassLoader classLoader) {
- setClassLoader(classLoader);
- if (StringUtils.hasText(beanNameGenerator)) {
- this.beanNameGenerator = beanNameGenerator;
- }
- return this;
- }
-
- BeanNameGenerator beanNameGenerator() {
- return nullSafeTypedObject(this.beanNameGenerator, BeanNameGenerator.class);
- }
-
- public ComponentScanSpec scopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {
- this.scopeMetadataResolver = scopeMetadataResolver;
- return this;
- }
-
- ComponentScanSpec scopeMetadataResolver(String scopeMetadataResolver, ClassLoader classLoader) {
- setClassLoader(classLoader);
- if (StringUtils.hasText(scopeMetadataResolver)) {
- this.scopeMetadataResolver = scopeMetadataResolver;
- }
- return this;
- }
-
- ScopeMetadataResolver scopeMetadataResolver() {
- return nullSafeTypedObject(this.scopeMetadataResolver, ScopeMetadataResolver.class);
- }
-
- public ComponentScanSpec scopedProxyMode(ScopedProxyMode scopedProxyMode) {
- this.scopedProxyMode = scopedProxyMode;
- return this;
- }
-
- ComponentScanSpec scopedProxyMode(String scopedProxyMode) {
- if (StringUtils.hasText(scopedProxyMode)) {
- this.scopedProxyMode = scopedProxyMode;
- }
- return this;
- }
-
- ScopedProxyMode scopedProxyMode() {
- return nullSafeTypedObject(this.scopedProxyMode, ScopedProxyMode.class);
- }
-
- public ComponentScanSpec useDefaultFilters(Boolean useDefaultFilters) {
- this.useDefaultFilters = useDefaultFilters;
- return this;
- }
-
- ComponentScanSpec useDefaultFilters(String useDefaultFilters) {
- if (StringUtils.hasText(useDefaultFilters)) {
- this.useDefaultFilters = Boolean.valueOf(useDefaultFilters);
- }
- return this;
- }
-
- Boolean useDefaultFilters() {
- return this.useDefaultFilters;
- }
-
- public ComponentScanSpec includeFilters(TypeFilter... includeFilters) {
- this.includeFilters.clear();
- for (TypeFilter filter : includeFilters) {
- addIncludeFilter(filter);
- }
- return this;
- }
-
- ComponentScanSpec addIncludeFilter(TypeFilter includeFilter) {
- Assert.notNull(includeFilter, "includeFilter must not be null");
- this.includeFilters.add(includeFilter);
- return this;
- }
-
- ComponentScanSpec addIncludeFilter(String filterType, String expression, ClassLoader classLoader) {
- this.includeFilters.add(new FilterTypeDescriptor(filterType, expression, classLoader));
- return this;
- }
-
- TypeFilter[] includeFilters() {
- return this.includeFilters.toArray(new TypeFilter[this.includeFilters.size()]);
- }
-
- public ComponentScanSpec excludeFilters(TypeFilter... excludeFilters) {
- this.excludeFilters.clear();
- for (TypeFilter filter : excludeFilters) {
- addExcludeFilter(filter);
- }
- return this;
- }
-
- ComponentScanSpec addExcludeFilter(TypeFilter excludeFilter) {
- Assert.notNull(excludeFilter, "excludeFilter must not be null");
- this.excludeFilters.add(excludeFilter);
- return this;
- }
-
- ComponentScanSpec addExcludeFilter(String filterType, String expression, ClassLoader classLoader) {
- this.excludeFilters.add(new FilterTypeDescriptor(filterType, expression, classLoader));
- return this;
- }
-
- TypeFilter[] excludeFilters() {
- return this.excludeFilters.toArray(new TypeFilter[this.excludeFilters.size()]);
- }
-
- ComponentScanSpec beanDefinitionDefaults(BeanDefinitionDefaults beanDefinitionDefaults) {
- this.beanDefinitionDefaults = beanDefinitionDefaults;
- return this;
- }
-
- BeanDefinitionDefaults beanDefinitionDefaults() {
- return this.beanDefinitionDefaults;
- }
-
- ComponentScanSpec autowireCandidatePatterns(String[] autowireCandidatePatterns) {
- this.autowireCandidatePatterns = autowireCandidatePatterns;
- return this;
- }
-
- String[] autowireCandidatePatterns() {
- return this.autowireCandidatePatterns;
- }
-
-
- /**
- * Create a ComponentScanSpec from a single string containing
- * delimited package names.
- * @see ConfigurableApplicationContext#CONFIG_LOCATION_DELIMITERS
- */
- static ComponentScanSpec forDelimitedPackages(String basePackages) {
- Assert.notNull(basePackages, "base packages must not be null");
- return new ComponentScanSpec(
- StringUtils.tokenizeToStringArray(basePackages,
- ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
- }
-
- public void doValidate(ProblemCollector problems) {
- if(this.basePackages.isEmpty()) {
- problems.error("At least one base package must be specified");
- }
-
- if(this.beanNameGenerator instanceof String) {
- this.beanNameGenerator = instantiateUserDefinedType("bean name generator", BeanNameGenerator.class, this.beanNameGenerator, this.classLoader, problems);
- }
-
- if(this.scopeMetadataResolver instanceof String) {
- this.scopeMetadataResolver = instantiateUserDefinedType("scope metadata resolver", ScopeMetadataResolver.class, this.scopeMetadataResolver, this.classLoader, problems);
- }
-
- if (this.scopedProxyMode instanceof String) {
- if ("targetClass".equalsIgnoreCase((String)this.scopedProxyMode)) {
- this.scopedProxyMode = ScopedProxyMode.TARGET_CLASS;
- }
- else if ("interfaces".equalsIgnoreCase((String)this.scopedProxyMode)) {
- this.scopedProxyMode = ScopedProxyMode.INTERFACES;
- }
- else if ("no".equalsIgnoreCase((String)this.scopedProxyMode)) {
- this.scopedProxyMode = ScopedProxyMode.NO;
- }
- else {
- problems.error("invalid scoped proxy mode [%s] supported modes are " +
- "'no', 'interfaces' and 'targetClass'");
- this.scopedProxyMode = null;
- }
- }
-
- if (this.scopeMetadataResolver != null && this.scopedProxyMode != null) {
- problems.error("Cannot define both scope metadata resolver and scoped proxy mode");
- }
-
- for (int i = 0; i < this.includeFilters.size(); i++) {
- if (this.includeFilters.get(i) instanceof FilterTypeDescriptor) {
- this.includeFilters.set(i, ((FilterTypeDescriptor)this.includeFilters.get(i)).createTypeFilter(problems));
- }
- }
-
- for (int i = 0; i < this.excludeFilters.size(); i++) {
- if (this.excludeFilters.get(i) instanceof FilterTypeDescriptor) {
- this.excludeFilters.set(i, ((FilterTypeDescriptor)this.excludeFilters.get(i)).createTypeFilter(problems));
- }
- }
- }
-
- private static Object instantiateUserDefinedType(String description, Class<?> targetType, Object className, ClassLoader classLoader, ProblemCollector problems) {
- Assert.isInstanceOf(String.class, className, "userType must be of type String");
- Assert.notNull(classLoader, "classLoader must not be null");
- Assert.notNull(targetType, "targetType must not be null");
- Object instance = null;
- try {
- instance = classLoader.loadClass((String)className).newInstance();
- if (!targetType.isAssignableFrom(instance.getClass())) {
- problems.error(description + " class name must be assignable to " + targetType.getSimpleName());
- instance = null;
- }
- }
- catch (ClassNotFoundException ex) {
- problems.error(String.format(description + " class [%s] not found", className), ex);
- }
- catch (Exception ex) {
- problems.error(String.format("Unable to instantiate %s class [%s] for " +
- "strategy [%s]. Has a no-argument constructor been provided?",
- description, className, targetType.getClass().getSimpleName()), ex);
- }
- return instance;
- }
-
- private void setClassLoader(ClassLoader classLoader) {
- Assert.notNull(classLoader, "classLoader must not be null");
- if (this.classLoader == null) {
- this.classLoader = classLoader;
- }
- else {
- Assert.isTrue(this.classLoader == classLoader, "A classLoader has already been assigned " +
- "and the supplied classLoader is not the same instance. Use the same classLoader " +
- "for all string-based class properties.");
- }
- }
-
- @SuppressWarnings("unchecked")
- private static <T> T nullSafeTypedObject(Object object, Class<T> type) {
- if (object != null) {
- if (!(type.isAssignableFrom(object.getClass()))) {
- throw new IllegalStateException(
- String.format("field must be of type %s but was actually of type %s", type, object.getClass()));
- }
- }
- return (T)object;
- }
-
- private static String[] packagesFor(Class<?>[] classes) {
- ArrayList<String> packages = new ArrayList<String>();
- for (Class<?> clazz : classes) {
- packages.add(clazz.getPackage().getName());
- }
- return packages.toArray(new String[packages.size()]);
- }
-
-
- private static class FilterTypeDescriptor {
- private String filterType;
- private String expression;
- private ClassLoader classLoader;
-
- FilterTypeDescriptor(String filterType, String expression, ClassLoader classLoader) {
- Assert.notNull(filterType, "filterType must not be null");
- Assert.notNull(expression, "expression must not be null");
- Assert.notNull(classLoader, "classLoader must not be null");
- this.filterType = filterType;
- this.expression = expression;
- this.classLoader = classLoader;
- }
-
- @SuppressWarnings("unchecked")
- TypeFilter createTypeFilter(ProblemCollector problems) {
- try {
- if ("annotation".equalsIgnoreCase(this.filterType)) {
- return new AnnotationTypeFilter((Class<Annotation>) this.classLoader.loadClass(this.expression));
- }
- else if ("assignable".equalsIgnoreCase(this.filterType)
- || "assignable_type".equalsIgnoreCase(this.filterType)) {
- return new AssignableTypeFilter(this.classLoader.loadClass(this.expression));
- }
- else if ("aspectj".equalsIgnoreCase(this.filterType)) {
- return new AspectJTypeFilter(this.expression, this.classLoader);
- }
- else if ("regex".equalsIgnoreCase(this.filterType)) {
- return new RegexPatternTypeFilter(Pattern.compile(this.expression));
- }
- else if ("custom".equalsIgnoreCase(this.filterType)) {
- Class<?> filterClass = this.classLoader.loadClass(this.expression);
- if (!TypeFilter.class.isAssignableFrom(filterClass)) {
- problems.error(String.format("custom type filter class [%s] must be assignable to %s",
- this.expression, TypeFilter.class));
- }
- return (TypeFilter) BeanUtils.instantiateClass(filterClass);
- }
- else {
- problems.error(String.format("Unsupported filter type [%s]; supported types are: " +
- "'annotation', 'assignable[_type]', 'aspectj', 'regex', 'custom'", this.filterType));
- }
- } catch (ClassNotFoundException ex) {
- problems.error("Type filter class not found: " + this.expression, ex);
- } catch (Exception ex) {
- problems.error(ex.getMessage(), ex.getCause());
- }
-
- return new PlaceholderTypeFilter();
- }
-
-
- private class PlaceholderTypeFilter implements TypeFilter {
-
- public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
- throws IOException {
- throw new UnsupportedOperationException(
- String.format("match() method for placeholder type filter for " +
- "{filterType=%s,expression=%s} should never be invoked",
- filterType, expression));
- }
-
- }
- }
-
-
-} | true |
Other | spring-projects | spring-framework | 111fb71fe1ccb8d3a5e06e61461edd87d6d025f4.json | Remove "Feature" support introduced in 3.1 M1
Feature-related support such as @Feature, @FeatureConfiguration,
and FeatureSpecification types will be replaced by framework-provided
@Configuration classes and convenience annotations such as
@ComponentScan (already exists), @EnableAsync, @EnableScheduling,
@EnableTransactionManagement and others.
Issue: SPR-8012,SPR-8034,SPR-8039,SPR-8188,SPR-8206,SPR-8223,
SPR-8225,SPR-8226,SPR-8227 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java | @@ -33,7 +33,6 @@
import org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
-import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.parsing.Location;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.beans.factory.parsing.ProblemReporter;
@@ -45,8 +44,8 @@
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
-import org.springframework.context.config.FeatureSpecification;
-import org.springframework.context.config.SpecificationContext;
+import org.springframework.context.EnvironmentAware;
+import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.Conventions;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
@@ -94,7 +93,7 @@ public class ConfigurationClassBeanDefinitionReader {
private ResourceLoader resourceLoader;
- private SpecificationContext specificationContext;
+ private Environment environment;
/**
* Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
@@ -111,13 +110,7 @@ public ConfigurationClassBeanDefinitionReader(final BeanDefinitionRegistry regis
this.problemReporter = problemReporter;
this.metadataReaderFactory = metadataReaderFactory;
this.resourceLoader = resourceLoader;
- // TODO SPR-7420: see about passing in the SpecificationContext created in ConfigurationClassPostProcessor
- this.specificationContext = new SpecificationContext();
- this.specificationContext.setRegistry(this.registry);
- this.specificationContext.setRegistrar(new SimpleComponentRegistrar(this.registry));
- this.specificationContext.setResourceLoader(this.resourceLoader);
- this.specificationContext.setEnvironment(environment);
- this.specificationContext.setProblemReporter(problemReporter);
+ this.environment = environment;
}
@@ -137,35 +130,13 @@ public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
*/
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
AnnotationMetadata metadata = configClass.getMetadata();
- processFeatureAnnotations(metadata);
doLoadBeanDefinitionForConfigurationClassIfNecessary(configClass);
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
loadBeanDefinitionsForBeanMethod(beanMethod);
}
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
}
- private void processFeatureAnnotations(AnnotationMetadata metadata) {
- try {
- for (String annotationType : metadata.getAnnotationTypes()) {
- MetadataReader metadataReader = new SimpleMetadataReaderFactory().getMetadataReader(annotationType);
- if (metadataReader.getAnnotationMetadata().isAnnotated(FeatureAnnotation.class.getName())) {
- Map<String, Object> annotationAttributes = metadataReader.getAnnotationMetadata().getAnnotationAttributes(FeatureAnnotation.class.getName(), true);
- // TODO SPR-7420: this is where we can catch user-defined types and avoid instantiating them for STS purposes
- FeatureAnnotationParser processor = (FeatureAnnotationParser) BeanUtils.instantiateClass(Class.forName((String)annotationAttributes.get("parser")));
- FeatureSpecification spec = processor.process(metadata);
- spec.execute(this.specificationContext);
- }
- }
- } catch (BeanDefinitionParsingException ex) {
- throw ex;
- }
- catch (Exception ex) {
- // TODO SPR-7420: what exception to throw?
- throw new RuntimeException(ex);
- }
- }
-
/**
* Register the {@link Configuration} class itself as a bean definition.
*/
@@ -200,7 +171,7 @@ private void doLoadBeanDefinitionForConfigurationClassIfNecessary(ConfigurationC
}
/**
- * Read a particular {@link BeanMethod}, registering bean definitions
+ * Read the given {@link BeanMethod}, registering bean definitions
* with the BeanDefinitionRegistry based on its contents.
*/
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
@@ -423,8 +394,8 @@ public ConfigurationClassBeanDefinition cloneBeanDefinition() {
*/
private static class InvalidConfigurationImportProblem extends Problem {
public InvalidConfigurationImportProblem(String className, Resource resource, AnnotationMetadata metadata) {
- super(String.format("%s was @Import'ed but is not annotated with @FeatureConfiguration or " +
- "@Configuration nor does it declare any @Bean methods. Update the class to " +
+ super(String.format("%s was @Import'ed but is not annotated with @Configuration " +
+ "nor does it declare any @Bean methods. Update the class to " +
"meet one of these requirements or do not attempt to @Import it.", className),
new Location(resource, metadata));
} | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.