diff --git a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java index 3bb8e2d6678..7f1cebd0d6b 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java @@ -371,6 +371,29 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean return pvs; } + /** + * 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 supported 'resource' annotation types. + * @param bean the target instance to process + * @throws BeanCreationException if resource injection failed + * @since 6.1.3 + */ + public void processInjection(Object bean) throws BeanCreationException { + Class clazz = bean.getClass(); + InjectionMetadata metadata = findResourceMetadata(clazz.getName(), clazz, null); + try { + metadata.inject(bean, null, null); + } + catch (BeanCreationException ex) { + throw ex; + } + catch (Throwable ex) { + throw new BeanCreationException( + "Injection of resource dependencies failed for class [" + clazz + "]", ex); + } + } + private InjectionMetadata findResourceMetadata(String beanName, Class clazz, @Nullable PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java index 5ab7b83a7c7..b08c67573eb 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java @@ -52,6 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Juergen Hoeller * @author Chris Beams + * @author Sam Brannen */ class CommonAnnotationBeanPostProcessorTests { @@ -65,6 +66,20 @@ class CommonAnnotationBeanPostProcessorTests { bf.addBeanPostProcessor(bpp); } + @Test + void processInjection() { + ResourceInjectionBean bean = new ResourceInjectionBean(); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); + + TestBean tb = new TestBean(); + bf.registerSingleton("testBean", tb); + bpp.processInjection(bean); + + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + } + @Test void postConstructAndPreDestroy() { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedInitDestroyBean.class));