Early removal of 5.x-deprecated code

Closes gh-27686
This commit is contained in:
Juergen Hoeller
2021-11-18 09:18:06 +01:00
parent 17cdd97c37
commit 4750a9430c
132 changed files with 89 additions and 9216 deletions

View File

@@ -1,84 +0,0 @@
/*
* Copyright 2002-2019 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
*
* https://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.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringValueResolver;
/**
* General utility methods for working with annotations in JavaBeans style.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @deprecated as of 5.2, in favor of custom annotation attribute processing
*/
@Deprecated
public abstract class AnnotationBeanUtils {
/**
* Copy the properties of the supplied {@link Annotation} to the supplied target bean.
* Any properties defined in {@code excludedProperties} will not be copied.
* @param ann the annotation to copy from
* @param bean the bean instance to copy to
* @param excludedProperties the names of excluded properties, if any
* @see org.springframework.beans.BeanWrapper
*/
public static void copyPropertiesToBean(Annotation ann, Object bean, String... excludedProperties) {
copyPropertiesToBean(ann, bean, null, excludedProperties);
}
/**
* Copy the properties of the supplied {@link Annotation} to the supplied target bean.
* Any properties defined in {@code excludedProperties} will not be copied.
* <p>A specified value resolver may resolve placeholders in property values, for example.
* @param ann the annotation to copy from
* @param bean the bean instance to copy to
* @param valueResolver a resolve to post-process String property values (may be {@code null})
* @param excludedProperties the names of excluded properties, if any
* @see org.springframework.beans.BeanWrapper
*/
public static void copyPropertiesToBean(Annotation ann, Object bean, @Nullable StringValueResolver valueResolver,
String... excludedProperties) {
Set<String> excluded = (excludedProperties.length == 0 ? Collections.emptySet() :
new HashSet<>(Arrays.asList(excludedProperties)));
Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
for (Method annotationProperty : annotationProperties) {
String propertyName = annotationProperty.getName();
if (!excluded.contains(propertyName) && bw.isWritableProperty(propertyName)) {
Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
if (valueResolver != null && value instanceof String) {
value = valueResolver.resolveStringValue((String) value);
}
bw.setPropertyValue(propertyName, value);
}
}
}
}

View File

@@ -1,9 +0,0 @@
/**
* Support package for beans-style handling of Java 5 annotations.
*/
@NonNullApi
@NonNullFields
package org.springframework.beans.annotation;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@@ -419,14 +419,6 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
return pvs;
}
@Deprecated
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
return postProcessProperties(pvs, bean, beanName);
}
/**
* 'Native' processing method for direct calls with an arbitrary target instance,
* resolving all of its fields and methods which are annotated with one of the

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a method (typically a JavaBean setter method) as being 'required': that is,
* the setter method must be configured to be dependency-injected with a value.
*
* <p>Please do consult the javadoc for the {@link RequiredAnnotationBeanPostProcessor}
* class (which, by default, checks for the presence of this annotation).
*
* @author Rob Harrop
* @since 2.0
* @see RequiredAnnotationBeanPostProcessor
* @deprecated as of 5.1, in favor of using constructor injection for required settings
* (or a custom {@link org.springframework.beans.factory.InitializingBean} implementation)
*/
@Deprecated
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Required {
}

View File

@@ -1,230 +0,0 @@
/*
* Copyright 2002-2021 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
*
* https://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.annotation;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.Conventions;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
* that enforces required JavaBean properties to have been configured.
* Required bean properties are detected through a Java 5 annotation:
* by default, Spring's {@link Required} annotation.
*
* <p>The motivation for the existence of this BeanPostProcessor is to allow
* developers to annotate the setter properties of their own classes with an
* arbitrary JDK 1.5 annotation to indicate that the container must check
* for the configuration of a dependency injected value. This neatly pushes
* responsibility for such checking onto the container (where it arguably belongs),
* and obviates the need (<b>in part</b>) for a developer to code a method that
* simply checks that all required properties have actually been set.
*
* <p>Please note that an 'init' method may still need to be implemented (and may
* still be desirable), because all that this class does is enforcing that a
* 'required' property has actually been configured with a value. It does
* <b>not</b> check anything else... In particular, it does not check that a
* configured value is not {@code null}.
*
* <p>Note: A default RequiredAnnotationBeanPostProcessor will be registered
* by the "context:annotation-config" and "context:component-scan" XML tags.
* Remove or turn off the default annotation configuration there if you intend
* to specify a custom RequiredAnnotationBeanPostProcessor bean definition.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see #setRequiredAnnotationType
* @see Required
* @deprecated as of 5.1, in favor of using constructor injection for required settings
* (or a custom {@link org.springframework.beans.factory.InitializingBean} implementation)
*/
@Deprecated
public class RequiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
/**
* Bean definition attribute that may indicate whether a given bean is supposed
* to be skipped when performing this post-processor's required property check.
* @see #shouldSkip
*/
public static final String SKIP_REQUIRED_CHECK_ATTRIBUTE =
Conventions.getQualifiedAttributeName(RequiredAnnotationBeanPostProcessor.class, "skipRequiredCheck");
private Class<? extends Annotation> requiredAnnotationType = Required.class;
private int order = Ordered.LOWEST_PRECEDENCE - 1;
@Nullable
private ConfigurableListableBeanFactory beanFactory;
/**
* Cache for validated bean names, skipping re-validation for the same bean.
*/
private final Set<String> validatedBeanNames = Collections.newSetFromMap(new ConcurrentHashMap<>(64));
/**
* Set the 'required' annotation type, to be used on bean property
* setter methods.
* <p>The default required annotation type is the Spring-provided
* {@link Required} annotation.
* <p>This setter property exists so that developers can provide their own
* (non-Spring-specific) annotation type to indicate that a property value
* is required.
*/
public void setRequiredAnnotationType(Class<? extends Annotation> requiredAnnotationType) {
Assert.notNull(requiredAnnotationType, "'requiredAnnotationType' must not be null");
this.requiredAnnotationType = requiredAnnotationType;
}
/**
* Return the 'required' annotation type.
*/
protected Class<? extends Annotation> getRequiredAnnotationType() {
return this.requiredAnnotationType;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
}
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
if (!this.validatedBeanNames.contains(beanName)) {
if (!shouldSkip(this.beanFactory, beanName)) {
List<String> invalidProperties = new ArrayList<>();
for (PropertyDescriptor pd : pds) {
if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) {
invalidProperties.add(pd.getName());
}
}
if (!invalidProperties.isEmpty()) {
throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName));
}
}
this.validatedBeanNames.add(beanName);
}
return pvs;
}
/**
* Check whether the given bean definition is not subject to the annotation-based
* required property check as performed by this post-processor.
* <p>The default implementations check for the presence of the
* {@link #SKIP_REQUIRED_CHECK_ATTRIBUTE} attribute in the bean definition, if any.
* It also suggests skipping in case of a bean definition with a "factory-bean"
* reference set, assuming that instance-based factories pre-populate the bean.
* @param beanFactory the BeanFactory to check against
* @param beanName the name of the bean to check against
* @return {@code true} to skip the bean; {@code false} to process it
*/
protected boolean shouldSkip(@Nullable ConfigurableListableBeanFactory beanFactory, String beanName) {
if (beanFactory == null || !beanFactory.containsBeanDefinition(beanName)) {
return false;
}
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (beanDefinition.getFactoryBeanName() != null) {
return true;
}
Object value = beanDefinition.getAttribute(SKIP_REQUIRED_CHECK_ATTRIBUTE);
return (value != null && (Boolean.TRUE.equals(value) || Boolean.parseBoolean(value.toString())));
}
/**
* Is the supplied property required to have a value (that is, to be dependency-injected)?
* <p>This implementation looks for the existence of a
* {@link #setRequiredAnnotationType "required" annotation}
* on the supplied {@link PropertyDescriptor property}.
* @param propertyDescriptor the target PropertyDescriptor (never {@code null})
* @return {@code true} if the supplied property has been marked as being required;
* {@code false} if not, or if the supplied property does not have a setter method
*/
protected boolean isRequiredProperty(PropertyDescriptor propertyDescriptor) {
Method setter = propertyDescriptor.getWriteMethod();
return (setter != null && AnnotationUtils.getAnnotation(setter, getRequiredAnnotationType()) != null);
}
/**
* Build an exception message for the given list of invalid properties.
* @param invalidProperties the list of names of invalid properties
* @param beanName the name of the bean
* @return the exception message
*/
private String buildExceptionMessage(List<String> invalidProperties, String beanName) {
int size = invalidProperties.size();
StringBuilder sb = new StringBuilder();
sb.append(size == 1 ? "Property" : "Properties");
for (int i = 0; i < size; i++) {
String propertyName = invalidProperties.get(i);
if (i > 0) {
if (i == (size - 1)) {
sb.append(" and");
}
else {
sb.append(',');
}
}
sb.append(" '").append(propertyName).append('\'');
}
sb.append(size == 1 ? " is" : " are");
sb.append(" required for bean '").append(beanName).append('\'');
return sb.toString();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@@ -220,26 +220,6 @@ public class DependencyDescriptor extends InjectionPoint implements Serializable
throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
}
/**
* Resolve the specified not-unique scenario: by default,
* throwing a {@link NoUniqueBeanDefinitionException}.
* <p>Subclasses may override this to select one of the instances or
* to opt out with no result at all through returning {@code null}.
* @param type the requested bean type
* @param matchingBeans a map of bean names and corresponding bean
* instances which have been pre-selected for the given type
* (qualifiers etc already applied)
* @return a bean instance to proceed with, or {@code null} for none
* @throws BeansException in case of the not-unique scenario being fatal
* @since 4.3
* @deprecated as of 5.1, in favor of {@link #resolveNotUnique(ResolvableType, Map)}
*/
@Deprecated
@Nullable
public Object resolveNotUnique(Class<?> type, Map<String, Object> matchingBeans) throws BeansException {
throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
}
/**
* Resolve a shortcut for this dependency against the given factory, for example
* taking some pre-resolved information into account.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.beans.factory.config;
import java.beans.PropertyDescriptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.lang.Nullable;
@@ -34,9 +32,7 @@ import org.springframework.lang.Nullable;
*
* <p><b>NOTE:</b> This interface is a special purpose interface, mainly for
* internal use within the framework. It is recommended to implement the plain
* {@link BeanPostProcessor} interface as far as possible, or to derive from
* {@link InstantiationAwareBeanPostProcessorAdapter} in order to be shielded
* from extensions to this interface.
* {@link BeanPostProcessor} interface as far as possible.
*
* @author Juergen Hoeller
* @author Rod Johnson
@@ -96,53 +92,19 @@ public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
/**
* Post-process the given property values before the factory applies them
* to the given bean, without any need for property descriptors.
* <p>Implementations should return {@code null} (the default) if they provide a custom
* {@link #postProcessPropertyValues} implementation, and {@code pvs} otherwise.
* In a future version of this interface (with {@link #postProcessPropertyValues} removed),
* the default implementation will return the given {@code pvs} as-is directly.
* @param pvs the property values that the factory is about to apply (never {@code null})
* @param bean the bean instance created, but whose properties have not yet been set
* @param beanName the name of the bean
* @return the actual property values to apply to the given bean (can be the passed-in
* PropertyValues instance), or {@code null} which proceeds with the existing properties
* but specifically continues with a call to {@link #postProcessPropertyValues}
* (requiring initialized {@code PropertyDescriptor}s for the current bean class)
* @throws org.springframework.beans.BeansException in case of errors
* @since 5.1
* @see #postProcessPropertyValues
*/
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return null;
}
/**
* Post-process the given property values before the factory applies them
* to the given bean. Allows for checking whether all dependencies have been
* satisfied, for example based on a "Required" annotation on bean property setters.
* <p>Also allows for replacing the property values to apply, typically through
* creating a new MutablePropertyValues instance based on the original PropertyValues,
* adding or removing specific values.
* to the given bean.
* <p>The default implementation returns the given {@code pvs} as-is.
* @param pvs the property values that the factory is about to apply (never {@code null})
* @param pds the relevant property descriptors for the target bean (with ignored
* dependency types - which the factory handles specifically - already filtered out)
* @param bean the bean instance created, but whose properties have not yet been set
* @param beanName the name of the bean
* @return the actual property values to apply to the given bean (can be the passed-in
* PropertyValues instance), or {@code null} to skip property population
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessProperties
* @see org.springframework.beans.MutablePropertyValues
* @deprecated as of 5.1, in favor of {@link #postProcessProperties(PropertyValues, Object, String)}
* @since 5.1
*/
@Deprecated
@Nullable
default PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return pvs;
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2002-2020 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
*
* https://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.config;
/**
* Adapter that implements all methods on {@link SmartInstantiationAwareBeanPostProcessor}
* as no-ops, which will not change normal processing of each bean instantiated
* by the container. Subclasses may override merely those methods that they are
* actually interested in.
*
* <p>Note that this base class is only recommendable if you actually require
* {@link InstantiationAwareBeanPostProcessor} functionality. If all you need
* is plain {@link BeanPostProcessor} functionality, prefer a straight
* implementation of that (simpler) interface.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 2.0
* @deprecated as of 5.3 in favor of implementing {@link InstantiationAwareBeanPostProcessor}
* or {@link SmartInstantiationAwareBeanPostProcessor} directly.
*/
@Deprecated
public abstract class InstantiationAwareBeanPostProcessorAdapter implements SmartInstantiationAwareBeanPostProcessor {
}

View File

@@ -936,24 +936,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
return finder.getResult();
}
/**
* This implementation attempts to query the FactoryBean's generic parameter metadata
* if present to determine the object type. If not present, i.e. the FactoryBean is
* declared as a raw type, checks the FactoryBean's {@code getObjectType} 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).
* <p>The shortcut check for a FactoryBean is only applied in case of a singleton
* FactoryBean. If the FactoryBean instance itself is not kept as singleton,
* it will be fully created to check the type of its exposed object.
*/
@Override
@Deprecated
@Nullable
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
return getTypeForFactoryBean(beanName, mbd, true).resolve();
}
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
@@ -1398,7 +1380,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
@@ -1406,21 +1387,13 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
return;
}
pvs = pvsToUse;
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
checkDependencies(beanName, mbd, filteredPds, pvs);
}

View File

@@ -1694,28 +1694,6 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
return ResolvableType.NONE;
}
/**
* Determine the bean type for the given FactoryBean definition, as far as possible.
* Only called if there is no singleton instance registered for the target bean already.
* <p>The default implementation creates the FactoryBean via {@code getBean}
* to call its {@code getObjectType} method. Subclasses are encouraged to optimize
* this, typically by just instantiating the FactoryBean but not populating it yet,
* trying whether its {@code getObjectType} method already returns a type.
* If no type found, a full FactoryBean creation as performed by this implementation
* should be used as fallback.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @return the type for the bean if determinable, or {@code null} otherwise
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
* @deprecated since 5.2 in favor of {@link #getTypeForFactoryBean(String, RootBeanDefinition, boolean)}
*/
@Nullable
@Deprecated
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
return getTypeForFactoryBean(beanName, mbd, true).resolve();
}
/**
* Mark the specified bean as already created (or about to be created).
* <p>This allows the bean factory to optimize its caching for repeated

View File

@@ -1,82 +0,0 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.xml;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.Resource;
/**
* Convenience extension of {@link DefaultListableBeanFactory} that reads bean definitions
* from an XML document. Delegates to {@link XmlBeanDefinitionReader} underneath; effectively
* equivalent to using an XmlBeanDefinitionReader with a DefaultListableBeanFactory.
*
* <p>The structure, element and attribute names of the required XML document
* are hard-coded in this class. (Of course a transform could be run if necessary
* to produce this format). "beans" doesn't need to be the root element of the XML
* document: This class will parse all bean definition elements in the XML file.
*
* <p>This class registers each bean definition with the {@link DefaultListableBeanFactory}
* superclass, and relies on the latter's implementation of the {@link BeanFactory} interface.
* It supports singletons, prototypes, and references to either of these kinds of bean.
* See {@code "spring-beans-3.x.xsd"} (or historically, {@code "spring-beans-2.0.dtd"}) for
* details on options and configuration style.
*
* <p><b>For advanced needs, consider using a {@link DefaultListableBeanFactory} with
* an {@link XmlBeanDefinitionReader}.</b> The latter allows for reading from multiple XML
* resources and is highly configurable in its actual XML parsing behavior.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @since 15 April 2001
* @see org.springframework.beans.factory.support.DefaultListableBeanFactory
* @see XmlBeanDefinitionReader
* @deprecated as of Spring 3.1 in favor of {@link DefaultListableBeanFactory} and
* {@link XmlBeanDefinitionReader}
*/
@Deprecated
@SuppressWarnings({"serial", "all"})
public class XmlBeanFactory extends DefaultListableBeanFactory {
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
/**
* Create a new XmlBeanFactory with the given resource,
* which must be parsable using DOM.
* @param resource the XML resource to load bean definitions from
* @throws BeansException in case of loading or parsing errors
*/
public XmlBeanFactory(Resource resource) throws BeansException {
this(resource, null);
}
/**
* Create a new XmlBeanFactory with the given input stream,
* which must be parsable using DOM.
* @param resource the XML resource to load bean definitions from
* @param parentBeanFactory parent bean factory
* @throws BeansException in case of loading or parsing errors
*/
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader.loadBeanDefinitions(resource);
}
}

View File

@@ -250,27 +250,6 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.subInjected).isTrue();
}
@Test
@SuppressWarnings("deprecation")
public void testExtendedResourceInjectionWithAtRequired() {
bf.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertThat(bean.getBeanFactory()).isSameAs(bf);
}
@Test
public void testOptionalResourceInjection() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalResourceInjectionBean.class));
@@ -2401,7 +2380,6 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@Override
@Autowired
@Required
@SuppressWarnings("deprecation")
public void setTestBean2(TestBean testBean2) {
super.setTestBean2(testBean2);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@@ -154,27 +154,6 @@ public class InjectAnnotationBeanPostProcessorTests {
assertThat(bean.getBeanFactory()).isSameAs(bf);
}
@Test
@SuppressWarnings("deprecation")
public void testExtendedResourceInjectionWithAtRequired() {
bf.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertThat(bean.getTestBean()).isSameAs(tb);
assertThat(bean.getTestBean2()).isSameAs(tb);
assertThat(bean.getTestBean3()).isSameAs(tb);
assertThat(bean.getTestBean4()).isSameAs(tb);
assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertThat(bean.getBeanFactory()).isSameAs(bf);
}
@Test
public void testConstructorResourceInjection() {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorResourceInjectionBean.class);
@@ -666,7 +645,6 @@ public class InjectAnnotationBeanPostProcessorTests {
@Override
@Inject
@Required
@SuppressWarnings("deprecation")
public void setTestBean2(TestBean testBean2) {
super.setTestBean2(testBean2);

View File

@@ -1,244 +0,0 @@
/*
* Copyright 2002-2019 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
*
* https://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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Harrop
* @author Chris Beams
* @since 2.0
*/
@Deprecated
public class RequiredAnnotationBeanPostProcessorTests {
@Test
public void testWithRequiredPropertyOmitted() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.addPropertyValue("name", "Rob Harrop")
.addPropertyValue("favouriteColour", "Blue")
.addPropertyValue("jobTitle", "Grand Poobah")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Property")
.withMessageContaining("age")
.withMessageContaining("testBean");
}
@Test
public void testWithThreeRequiredPropertiesOmitted() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.addPropertyValue("name", "Rob Harrop")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Properties")
.withMessageContaining("age")
.withMessageContaining("favouriteColour")
.withMessageContaining("jobTitle")
.withMessageContaining("testBean");
}
@Test
public void testWithAllRequiredPropertiesSpecified() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.addPropertyValue("age", "24")
.addPropertyValue("favouriteColour", "Blue")
.addPropertyValue("jobTitle", "Grand Poobah")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean");
assertThat(bean.getAge()).isEqualTo(24);
assertThat(bean.getFavouriteColour()).isEqualTo("Blue");
}
@Test
public void testWithCustomAnnotation() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
RequiredAnnotationBeanPostProcessor rabpp = new RequiredAnnotationBeanPostProcessor();
rabpp.setRequiredAnnotationType(MyRequired.class);
factory.addBeanPostProcessor(rabpp);
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Property")
.withMessageContaining("name")
.withMessageContaining("testBean");
}
@Test
public void testWithStaticFactoryMethod() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.setFactoryMethod("create")
.addPropertyValue("name", "Rob Harrop")
.addPropertyValue("favouriteColour", "Blue")
.addPropertyValue("jobTitle", "Grand Poobah")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Property")
.withMessageContaining("age")
.withMessageContaining("testBean");
}
@Test
public void testWithStaticFactoryMethodAndRequiredPropertiesSpecified() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.setFactoryMethod("create")
.addPropertyValue("age", "24")
.addPropertyValue("favouriteColour", "Blue")
.addPropertyValue("jobTitle", "Grand Poobah")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean");
assertThat(bean.getAge()).isEqualTo(24);
assertThat(bean.getFavouriteColour()).isEqualTo("Blue");
}
@Test
public void testWithFactoryBean() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
RootBeanDefinition beanDef = new RootBeanDefinition(RequiredTestBean.class);
beanDef.setFactoryBeanName("testBeanFactory");
beanDef.setFactoryMethodName("create");
factory.registerBeanDefinition("testBean", beanDef);
factory.registerBeanDefinition("testBeanFactory", new RootBeanDefinition(RequiredTestBeanFactory.class));
RequiredAnnotationBeanPostProcessor bpp = new RequiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(factory);
factory.addBeanPostProcessor(bpp);
factory.preInstantiateSingletons();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyRequired {
}
public static class RequiredTestBean implements BeanNameAware, BeanFactoryAware {
private String name;
private int age;
private String favouriteColour;
private String jobTitle;
public int getAge() {
return age;
}
@Required
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
@MyRequired
public void setName(String name) {
this.name = name;
}
public String getFavouriteColour() {
return favouriteColour;
}
@Required
public void setFavouriteColour(String favouriteColour) {
this.favouriteColour = favouriteColour;
}
public String getJobTitle() {
return jobTitle;
}
@Required
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
@Override
@Required
public void setBeanName(String name) {
}
@Override
@Required
public void setBeanFactory(BeanFactory beanFactory) {
}
public static RequiredTestBean create() {
return new RequiredTestBean();
}
}
public static class RequiredTestBeanFactory {
public RequiredTestBean create() {
return new RequiredTestBean();
}
}
}