Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2002-2007 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.annotation;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
org.springframework.beans.factory.config.BeanPostProcessor implementation that autowires annotated fields, setter methods and arbitrary config methods. Such members to be injected are detected through a Java 5 annotation: by default, Spring's Autowired annotation.

Only one constructor (at max) of any given bean class may carry this annotation with the 'required' parameter set to true, indicating the constructor to autowire when used as a Spring bean. If multiple non-required constructors carry the annotation, they will be considered as candidates for autowiring. The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen. If none of the candidates can be satisfied, then a default constructor (if present) will be used. An annotated constructor does not have to be public.

Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.

Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Such config methods do not have to be public.

Note: A default AutowiredAnnotationBeanPostProcessor 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 AutowiredAnnotationBeanPostProcessor bean definition.

Author(s):
Juergen Hoeller
Mark Fisher
Since:
2.5
See also:
setAutowiredAnnotationType(java.lang.Class)
Autowired
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
 
 
 	protected final Log logger = LogFactory.getLog(AutowiredAnnotationBeanPostProcessor.class);
 
 	private Class<? extends AnnotationautowiredAnnotationType = Autowired.class;
 	
 	private String requiredParameterName = "required";
	private boolean requiredParameterValue = true;
	private int order = .;  // default: same as non-Ordered
	private final Map<Class<?>, Constructor[]> candidateConstructorsCache =
Set the 'autowired' annotation type, to be used on constructors, fields, setter methods and arbitrary config methods.

The default autowired annotation type is the Spring-provided Autowired annotation.

This setter property exists so that developers can provide their own (non-Spring-specific) annotation type to indicate that a member is supposed to be autowired.

	public void setAutowiredAnnotationType(Class<? extends AnnotationautowiredAnnotationType) {
		Assert.notNull(autowiredAnnotationType"'autowiredAnnotationType' must not be null");
		this. = autowiredAnnotationType;
	}

Return the 'autowired' annotation type.
	protected Class<? extends AnnotationgetAutowiredAnnotationType() {
	}

Set the name of a parameter of the annotation that specifies whether it is required.

	public void setRequiredParameterName(String requiredParameterName) {
		this. = requiredParameterName;
	}

Set the boolean value that marks a dependency as required

For example if using 'required=true' (the default), this value should be true; but if using 'optional=false', this value should be false.

	public void setRequiredParameterValue(boolean requiredParameterValue) {
		this. = requiredParameterValue;
	}
	public void setOrder(int order) {
	  this. = order;
	}
	public int getOrder() {
	  return this.;
	}
	public void setBeanFactory(BeanFactory beanFactorythrows BeansException {
		if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
					"AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory");
		}
	}
	public Constructor[] determineCandidateConstructors(Class beanClassString beanNamethrows BeansException {
		// Quick check on the concurrent map first, with minimal locking.
		Constructor[] candidateConstructors = this..get(beanClass);
		if (candidateConstructors == null) {
			synchronized (this.) {
				candidateConstructors = this..get(beanClass);
				if (candidateConstructors == null) {
					Constructor[] rawCandidates = beanClass.getDeclaredConstructors();
					List<Constructorcandidates = new ArrayList<Constructor>(rawCandidates.length);
					Constructor requiredConstructor = null;
					Constructor defaultConstructor = null;
					for (int i = 0; i < rawCandidates.lengthi++) {
						Constructor<?> candidate = rawCandidates[i];
						if (annotation != null) {
							if (requiredConstructor != null) {
								throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate +
										". Found another constructor with 'required' Autowired annotation: " + requiredConstructor);
							}
							if (candidate.getParameterTypes().length == 0) {
								throw new IllegalStateException("Autowired annotation requires at least one argument: " + candidate);
							}
							boolean required = determineRequiredStatus(annotation);
							if (required) {
								if (!candidates.isEmpty()) {
									throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates +
											". Found another constructor with 'required' Autowired annotation: " + requiredConstructor);
								}
								requiredConstructor = candidate;
							}
							candidates.add(candidate);
						}
						else if (candidate.getParameterTypes().length == 0) {
							defaultConstructor = candidate;
						}
					}
					if (!candidates.isEmpty()) {
						// Add default constructor to list of optional constructors, as fallback.
						if (requiredConstructor == null && defaultConstructor != null) {
							candidates.add(defaultConstructor);
						}
						candidateConstructors = (Constructor[]) candidates.toArray(new Constructor[candidates.size()]);
					}
					else {
						candidateConstructors = new Constructor[0];
					}
					this..put(beanClasscandidateConstructors);
				}
			}
		}
		return (candidateConstructors.length > 0 ? candidateConstructors : null);
	}
	public boolean postProcessAfterInstantiation(Object beanString beanNamethrows BeansException {
		try {
			metadata.injectFields(beanbeanName);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName"Autowiring of fields failed"ex);
		}
		return true;
	}
			PropertyValues pvsPropertyDescriptor[] pdsObject beanString beanNamethrows BeansException {
		try {
			metadata.injectMethods(beanbeanNamepvs);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName"Autowiring of methods failed"ex);
		}
		return pvs;
	}
		// Quick check on the concurrent map first, with minimal locking.
		InjectionMetadata metadata = this..get(clazz);
		if (metadata == null) {
			synchronized (this.) {
				metadata = this..get(clazz);
				if (metadata == null) {
					final InjectionMetadata newMetadata = new InjectionMetadata();
					ReflectionUtils.doWithFields(clazznew ReflectionUtils.FieldCallback() {
						public void doWith(Field field) {
							if (annotation != null) {
								if (Modifier.isStatic(field.getModifiers())) {
									throw new IllegalStateException("Autowired annotation is not supported on static fields");
								}
								boolean required = determineRequiredStatus(annotation);
								newMetadata.addInjectedField(new AutowiredElement(fieldrequirednull));
							}
						}
					});
					ReflectionUtils.doWithMethods(clazznew ReflectionUtils.MethodCallback() {
						public void doWith(Method method) {
							if (annotation != null) {
								if (Modifier.isStatic(method.getModifiers())) {
									throw new IllegalStateException("Autowired annotation is not supported on static methods");
								}
								if (method.getParameterTypes().length == 0) {
									throw new IllegalStateException("Autowired annotation requires at least one argument: " + method);
								}
								boolean required = determineRequiredStatus(annotation);
								PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
								newMetadata.addInjectedMethod(new AutowiredElement(methodrequiredpd));
							}
						}
					});
					metadata = newMetadata;
					this..put(clazzmetadata);
				}
			}
		}
		return metadata;
	}

Obtain all beans of the given type as autowire candidates.

Parameters:
type the type of the bean
Returns:
the target beans, or an empty Collection if no bean of this type is found
Throws:
org.springframework.beans.BeansException if bean retrieval failed
	protected Map findAutowireCandidates(Class typethrows BeansException {
		if (this. == null) {
			throw new IllegalStateException("No BeanFactory configured - " +
					"override the getBeanOfType method or specify the 'beanFactory' property");
		}
		return BeanFactoryUtils.beansOfTypeIncludingAncestors(this.type);
	}

Determine if the annotated field or method requires its dependency.

A 'required' dependency means that autowiring should fail when no beans are found. Otherwise, the autowiring process will simply bypass the field or method when no beans are found.

Parameters:
annotation the Autowired annotation
Returns:
whether the annotation indicates that a dependency is required
	protected boolean determineRequiredStatus(Annotation annotation) {
		try {
			Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.);
			return (this. == (Boolean) ReflectionUtils.invokeMethod(methodannotation));
		}
		catch (Exception ex) {
			// required by default
			return true;
		}
	}


Class representing injection information about an annotated field or setter method.
		private final boolean required;
		private volatile String beanNameForField;
		private volatile String[] beanNamesForMethod;
		public AutowiredElement(Member memberboolean requiredPropertyDescriptor pd) {
			super(memberpd);
			this. = required;
		}
		protected void inject(Object beanString beanNamePropertyValues pvsthrows Throwable {
			if (this.) {
				return;
			}
			if (this.) {
				Field field = (Fieldthis.;
				try {
					Object argument = null;
					String determinedBeanName = this.;
					if (determinedBeanName != null) {
						argument = .getBean(determinedBeanName);
					}
					else {
						Set<StringautowiredBeanNames = new LinkedHashSet<String>(4);
								new DependencyDescriptor(fieldthis.),
								beanNameautowiredBeanNamestypeConverter);
						registerDependentBeans(beanNameautowiredBeanNames);
						if (autowiredBeanNames.size() == 1) {
							this. = autowiredBeanNames.iterator().next();
						}
					}
					if (argument != null) {
						ReflectionUtils.makeAccessible(field);
						field.set(beanargument);
					}
				}
				catch (Throwable ex) {
					throw new BeanCreationException("Could not autowire field: " + fieldex);
				}
			}
			else {
				if (this. != null && pvs != null && pvs.contains(this..getName())) {
					// Explicit value provided as part of the bean definition.
					this. = true;
					return;
				}
				Method method = (Methodthis.;
				Object[] arguments = new Object[method.getParameterTypes().length];
				try {
					String[] determinedBeanNames = this.;
					if (determinedBeanNames != null) {
						for (int i = 0; i < determinedBeanNames.lengthi++) {
							arguments[i] = .getBean(determinedBeanNames[i]);
						}
					}
					else {
						Set<StringautowiredBeanNames = new LinkedHashSet<String>(4);
						for (int i = 0; i < arguments.lengthi++) {
									new DependencyDescriptor(new MethodParameter(methodi), this.),
									beanNameautowiredBeanNamestypeConverter);
							if (arguments[i] == null) {
								arguments = null;
								break;
							}
						}
						if (arguments != null) {
							registerDependentBeans(beanNameautowiredBeanNames);
							if (autowiredBeanNames.size() == arguments.length) {
								this. = autowiredBeanNames.toArray(new String[arguments.length]);
							}
						}
					}
					if (arguments != null) {
						ReflectionUtils.makeAccessible(method);
						method.invoke(beanarguments);
					}
				}
					throw ex.getTargetException();
				}
				catch (Throwable ex) {
					throw new BeanCreationException("Could not autowire method: " + methodex);
				}
			}
		}
		private void registerDependentBeans(String beanNameSet<StringautowiredBeanNames) {
			for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) {
				String autowiredBeanName = (Stringit.next();
				.registerDependentBean(autowiredBeanNamebeanName);
					.debug("Autowiring by type from bean name '" + beanName + "' via " +
							(this. ? "field" : "configuration method") + " to bean named '" + autowiredBeanName + "'");
				}
			}
		}
	}
New to GrepCode? Check out our FAQ X