/** * Process {@code @Autowired} injection for the given target object, * based on the current web application context. * <p>Intended for use as a delegate. * @param target the target object to process * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext() */ public static void processInjectionBasedOnCurrentContext(Object target) { Assert.notNull(target, "Target object must not be null"); WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext(); if (cc != null) { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(cc.getAutowireCapableBeanFactory()); bpp.processInjection(target); } else { if (logger.isDebugEnabled()) { logger.debug("Current WebApplicationContext is not available for processing of " + ClassUtils.getShortName(target.getClass()) + ": " + "Make sure this class gets constructed in a Spring web application. Proceeding without injection."); } } }
@Test public void genericsBasedInjection() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(RepositoryInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); beanFactory.registerBeanDefinition("annotatedBean", bd); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(RepositoryConfiguration.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); assertEquals("Repository<String>", bean.stringRepository.toString()); assertEquals("Repository<Integer>", bean.integerRepository.toString()); }
@Test public void genericsBasedInjectionWithScoped() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(RepositoryInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); beanFactory.registerBeanDefinition("annotatedBean", bd); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(ScopedRepositoryConfiguration.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); assertEquals("Repository<String>", bean.stringRepository.toString()); assertEquals("Repository<Integer>", bean.integerRepository.toString()); }
@Test public void genericsBasedInjectionWithScopedProxy() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(RepositoryInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); beanFactory.registerBeanDefinition("annotatedBean", bd); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(ScopedProxyRepositoryConfiguration.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); beanFactory.freezeConfiguration(); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); assertEquals("Repository<String>", bean.stringRepository.toString()); assertEquals("Repository<Integer>", bean.integerRepository.toString()); assertTrue(AopUtils.isCglibProxy(bean.stringRepository)); assertTrue(AopUtils.isCglibProxy(bean.integerRepository)); }
@Test public void genericsBasedInjectionWithScopedProxyUsingAsm() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(RepositoryInjectionBean.class.getName()); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); beanFactory.registerBeanDefinition("annotatedBean", bd); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(ScopedProxyRepositoryConfiguration.class.getName())); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); beanFactory.freezeConfiguration(); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); assertEquals("Repository<String>", bean.stringRepository.toString()); assertEquals("Repository<Integer>", bean.integerRepository.toString()); assertTrue(AopUtils.isCglibProxy(bean.stringRepository)); assertTrue(AopUtils.isCglibProxy(bean.integerRepository)); }
@Test public void genericsBasedInjectionWithImplTypeAtInjectionPoint() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(SpecificRepositoryInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); beanFactory.registerBeanDefinition("annotatedBean", bd); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(SpecificRepositoryConfiguration.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); beanFactory.preInstantiateSingletons(); SpecificRepositoryInjectionBean bean = (SpecificRepositoryInjectionBean) beanFactory.getBean("annotatedBean"); assertSame(beanFactory.getBean("genericRepo"), bean.genericRepository); }
@Test public void genericsBasedInjectionWithFactoryBean() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(RepositoryFactoryBeanInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); beanFactory.registerBeanDefinition("annotatedBean", bd); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(RepositoryFactoryBeanConfiguration.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); beanFactory.preInstantiateSingletons(); RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) beanFactory.getBean("annotatedBean"); assertSame(beanFactory.getBean("&repoFactoryBean"), bean.repositoryFactoryBean); assertSame(beanFactory.getBean("&repoFactoryBean"), bean.qualifiedRepositoryFactoryBean); assertSame(beanFactory.getBean("&repoFactoryBean"), bean.prefixQualifiedRepositoryFactoryBean); }
@Test public void testCircularDependency() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); beanFactory.registerBeanDefinition("configClass1", new RootBeanDefinition(A.class)); beanFactory.registerBeanDefinition("configClass2", new RootBeanDefinition(AStrich.class)); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); try { beanFactory.preInstantiateSingletons(); fail("Should have thrown BeanCreationException"); } catch (BeanCreationException ex) { assertTrue(ex.getMessage().contains("Circular reference")); } }
@Test public void testLazyResourceInjectionWithNonExistingTarget() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(FieldResourceInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); bf.registerBeanDefinition("annotatedBean", bd); FieldResourceInjectionBean bean = (FieldResourceInjectionBean) bf.getBean("annotatedBean"); assertNotNull(bean.getTestBean()); try { bean.getTestBean().getName(); fail("Should have thrown NoSuchBeanDefinitionException"); } catch (NoSuchBeanDefinitionException ex) { // expected; } }
private void removeInjectCache(Object controller) { AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = ctx.getBean(AutowiredAnnotationBeanPostProcessor.class); Map<String, InjectionMetadata> injectionMetadataMap = (Map<String, InjectionMetadata>) ReflectionUtils.getField(injectionMetadataCacheField, autowiredAnnotationBeanPostProcessor); injectionMetadataMap.remove(controller.getClass().getName()); }
/** * Actually autowire the target bean after construction/passivation. * @param target the target bean to autowire */ protected void doAutowireBean(Object target) { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); configureBeanPostProcessor(bpp, target); bpp.setBeanFactory(getBeanFactory(target)); bpp.processInjection(target); }
@Test public void scopedProxyTargetMarkedAsNonAutowireCandidate() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); beanFactory.registerBeanDefinition("config", new RootBeanDefinition(ScopedProxyConfigurationClass.class)); beanFactory.registerBeanDefinition("consumer", new RootBeanDefinition(ScopedProxyConsumer.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); ITestBean injected = beanFactory.getBean("consumer", ScopedProxyConsumer.class).testBean; assertTrue(injected instanceof ScopedObject); assertSame(beanFactory.getBean("scopedClass"), injected); assertSame(beanFactory.getBean(ITestBean.class), injected); }
@Test public void testSelfReferenceExclusionForFactoryMethodOnSameBean() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor()); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(ConcreteConfig.class)); beanFactory.registerBeanDefinition("serviceBeanProvider", new RootBeanDefinition(ServiceBeanProvider.class)); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); beanFactory.preInstantiateSingletons(); beanFactory.getBean(ServiceBean.class); }
@Test public void testConfigWithDefaultMethods() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor()); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(ConcreteConfigWithDefaultMethods.class)); beanFactory.registerBeanDefinition("serviceBeanProvider", new RootBeanDefinition(ServiceBeanProvider.class)); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); beanFactory.preInstantiateSingletons(); beanFactory.getBean(ServiceBean.class); }
@Test public void testConfigWithDefaultMethodsUsingAsm() { AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(beanFactory); beanFactory.addBeanPostProcessor(bpp); beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor()); beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(ConcreteConfigWithDefaultMethods.class.getName())); beanFactory.registerBeanDefinition("serviceBeanProvider", new RootBeanDefinition(ServiceBeanProvider.class.getName())); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); beanFactory.preInstantiateSingletons(); beanFactory.getBean(ServiceBean.class); }
@Before public void setup() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("capitalizer", new RootBeanDefinition(Capitalizer.class)); instantiator = new SpringHandlerInstantiator(bf); objectMapper = Jackson2ObjectMapperBuilder.json().handlerInstantiator(instantiator).build(); }
@SuppressWarnings("unchecked") private AutowiredAnnotationResoved(ConfigurableListableBeanFactory beanFactory) { this.beanFactory = beanFactory; this.autowiredAnnotationTypes.add(Autowired.class); this.autowiredAnnotationTypes.add(Value.class); try { this.autowiredAnnotationTypes.add((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader())); log.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring"); } catch (ClassNotFoundException ex) { } }
public UserRegistrationSteps() { super(); SpringApplication application = new SpringApplication( RegistrationApplication.class); application.setWebEnvironment(false); AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor(); autowiredAnnotationBeanPostProcessor.setBeanFactory(application.run() .getBeanFactory()); autowiredAnnotationBeanPostProcessor.processInjection(this); }
@Override public BeanFactoryPostProcessor getBindings(LogInject<_Logger_> logInject) { return new BeanFactoryPostProcessor() { ThreadLocal<Object> injectee = new ThreadLocal<>(); @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory)beanFactory; AutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver() { @Override public Object getSuggestedValue(DependencyDescriptor descriptor) { if (descriptor.getDependencyType().equals(logInject.getLoggerClass())) { return logInject.createLogger(injectee.get().getClass()); } return null; } }; AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor() { @Override public PropertyValues postProcessPropertyValues(PropertyValues values, PropertyDescriptor[] descriptors, Object bean, String beanName) throws BeansException { injectee.set(bean); return super.postProcessPropertyValues(values, descriptors, bean, beanName); } }; beanPostProcessor.setBeanFactory(defaultListableBeanFactory); defaultListableBeanFactory.addBeanPostProcessor(beanPostProcessor); defaultListableBeanFactory.setAutowireCandidateResolver(resolver); } }; }
@Override public void onStart(Application application) { AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor(); beanPostProcessor.setBeanFactory(getApplicationContext(application).getBeanFactory()); beanPostProcessor.processInjection(this); }
@Override public void onStart() { AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor(); beanPostProcessor.setBeanFactory(getApplicationContext().getBeanFactory()); beanPostProcessor.processInjection(this); }
/** * Reset all post processors associated with a bean factory. * * @param beanFactory beanFactory to use */ public static void reset(DefaultListableBeanFactory beanFactory) { Class<?> c = getReflectionUtilsClassOrNull(); if (c != null) { try { Method m = c.getDeclaredMethod("clearCache"); m.invoke(c); } catch (Exception version42Failed) { try { // spring 4.0.x, 4.1.x without clearCache method, clear manually Field declaredMethodsCache = c.getDeclaredField("declaredMethodsCache"); declaredMethodsCache.setAccessible(true); ((Map)declaredMethodsCache.get(null)).clear(); Field declaredFieldsCache = c.getDeclaredField("declaredFieldsCache"); declaredFieldsCache.setAccessible(true); ((Map)declaredFieldsCache.get(null)).clear(); } catch (Exception version40Failed) { LOGGER.debug("Failed to clear internal method/field cache, it's normal with spring 4.1x or lower", version40Failed); } } LOGGER.trace("Cleared Spring 4.2+ internal method/field cache."); } for (BeanPostProcessor bpp : beanFactory.getBeanPostProcessors()) { if (bpp instanceof AutowiredAnnotationBeanPostProcessor) { resetAutowiredAnnotationBeanPostProcessorCache((AutowiredAnnotationBeanPostProcessor)bpp); } else if (bpp instanceof InitDestroyAnnotationBeanPostProcessor) { resetInitDestroyAnnotationBeanPostProcessorCache((InitDestroyAnnotationBeanPostProcessor)bpp); } } }
/** * Creates a <code>DefaultListableBeanFactory</code> with some default * settings, i.e. * <ul> * <li>support of auto-wiring annotation</li> * <li>disabled bean-overriding</li> * </ul> * * @param enableAutoWiring * <code>true</code> if auto-wiring for the factory should be * enabled, otherwise <code>false</code> * @param allowBeanOverriding * <code>true</code> if a bean can override another bean with the * same id, otherwise <code>false</code> * * @return a <code>DefaultListableBeanFactory</code> with some default * settings * * @see AutowiredAnnotationBeanPostProcessor * @see DefaultListableBeanFactory#setAllowBeanDefinitionOverriding */ public static DefaultListableBeanFactory createBeanFactory( final boolean enableAutoWiring, final boolean allowBeanOverriding) { // create the factory final DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.setAllowBeanDefinitionOverriding(allowBeanOverriding); // enable auto-wiring if (enableAutoWiring) { // get the resolver used for autowiring, we want the qualifier to be // used // when resolving final AutowireCandidateResolver resolver = new QualifierAnnotationAutowireCandidateResolver(); factory.setAutowireCandidateResolver(resolver); // now create the post processor and set the factory and the // resolver final AutowiredAnnotationBeanPostProcessor autowiredPostProcessor = new AutowiredAnnotationBeanPostProcessor(); autowiredPostProcessor.setBeanFactory(factory); factory.addBeanPostProcessor(autowiredPostProcessor); } factory.addPropertyEditorRegistrar(new ConfiguratorPropertyEditorRegistrar()); return factory; }
public void processInjection(Object bean) { AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor(); beanPostProcessor.setBeanFactory(getApplicationContext().getBeanFactory()); beanPostProcessor.processInjection(bean); }
private void injectOwnDependencies() { TestContext testContext = (TestContext) ReflectionTestUtils.getField(getTestContextManager(), TEST_CONTEXT_FIELD_IN_SPRING_JUNIT4_CLASS_RUNNER); ApplicationContext context = testContext.getApplicationContext(); context.getBean(AutowiredAnnotationBeanPostProcessor.class).processInjection(this); }
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; processer = new AutowiredAnnotationBeanPostProcessor(); processer.setBeanFactory(applicationContext.getAutowireCapableBeanFactory()); }
public final void injectMembers(Object instance) { final AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(getContext().getAutowireCapableBeanFactory()); bpp.processInjection(instance); }
@Bean public static AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor() { return new AutowiredAnnotationBeanPostProcessor(); }
/** * Process {@code @Autowired} injection for the given target object, * based on the current root web application context as stored in the ServletContext. * <p>Intended for use as a delegate. * @param target the target object to process * @param servletContext the ServletContext to find the Spring web application context in * @see WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext) */ public static void processInjectionBasedOnServletContext(Object target, ServletContext servletContext) { Assert.notNull(target, "Target object must not be null"); WebApplicationContext cc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(cc.getAutowireCapableBeanFactory()); bpp.processInjection(target); }
public void removeInjectCache(String name) { AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = ctx.getBean(AutowiredAnnotationBeanPostProcessor.class); Map<String, InjectionMetadata> injectionMetadataMap = (Map<String, InjectionMetadata>) ReflectionUtils.getField(injectionMetadataCacheField, autowiredAnnotationBeanPostProcessor); injectionMetadataMap.remove(name); }
/** * Template method for configuring the * {@link AutowiredAnnotationBeanPostProcessor} used for autowiring. * @param processor the AutowiredAnnotationBeanPostProcessor to configure * @param target the target bean to autowire with this processor */ protected void configureBeanPostProcessor(AutowiredAnnotationBeanPostProcessor processor, Object target) { }