@Override public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { Assert.notNull(otherFactory, "BeanFactory must not be null"); setBeanClassLoader(otherFactory.getBeanClassLoader()); setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); setBeanExpressionResolver(otherFactory.getBeanExpressionResolver()); if (otherFactory instanceof AbstractBeanFactory) { AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory; this.customEditors.putAll(otherAbstractFactory.customEditors); this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars); this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors); this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors || otherAbstractFactory.hasInstantiationAwareBeanPostProcessors; this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors || otherAbstractFactory.hasDestructionAwareBeanPostProcessors; this.scopes.putAll(otherAbstractFactory.scopes); this.securityContextProvider = otherAbstractFactory.securityContextProvider; } else { setTypeConverter(otherFactory.getTypeConverter()); } }
/** * Detect relationships in annotated {@link Bean @Bean} Factory methods. * * @return Relationships detected from factory methods. */ protected Set<Relationship> detectAnnotatedFactoryMethods() { Set<Relationship> result = new HashSet<>(); /* retrieve all beans declared in the application context */ String[] annotateBeans = applicationContext.getBeanDefinitionNames(); ConfigurableBeanFactory factory = applicationContext.getBeanFactory(); for (String beanName : annotateBeans) { /* ... and get the bean definition of each declared beans */ Optional<MethodMetadata> metadata = getMethodMetadata(factory.getMergedBeanDefinition(beanName)); if (metadata.isPresent()) { Set<Relationship> rel = detectMethodMetadata(metadata.get()); result.addAll(rel); } } return result; }
@Bean @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public AuditorAware<Username> auditorAware() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); log.debug("current authentication:" + authentication); if (authentication == null || !authentication.isAuthenticated()) { return () -> Optional.<Username>empty(); } return () -> Optional.of( Username.builder() .username(((UserDetails) authentication.getPrincipal()).getUsername()) .build() ); }
public HandlerMethodService(ConversionService conversionService, List<HandlerMethodArgumentResolver> customArgumentResolvers, ObjectMapper objectMapper, ApplicationContext applicationContext) { this.conversionService = conversionService; this.parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); this.argumentResolvers = new HandlerMethodArgumentResolverComposite(); ConfigurableBeanFactory beanFactory = ClassUtils.isAssignableValue( ConfigurableApplicationContext.class, applicationContext) ? ((ConfigurableApplicationContext) applicationContext) .getBeanFactory() : null; this.argumentResolvers.addResolver( new HeaderMethodArgumentResolver(this.conversionService, beanFactory)); this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver()); this.argumentResolvers.addResolver(new WampMessageMethodArgumentResolver()); this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver()); this.argumentResolvers.addResolver(new WampSessionIdMethodArgumentResolver()); this.argumentResolvers.addResolvers(customArgumentResolvers); this.objectMapper = objectMapper; }
@Override public void setBeanFactory(BeanFactory beanFactory) { if (!(beanFactory instanceof ConfigurableBeanFactory)) { throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory " + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass()); } this.beanFactory = (ConfigurableBeanFactory) beanFactory; // Required so that references (up container hierarchies) are correctly resolved. this.scriptBeanFactory.setParentBeanFactory(this.beanFactory); // Required so that all BeanPostProcessors, Scopes, etc become available. this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory); // Filter out BeanPostProcessors that are part of the AOP infrastructure, // since those are only meant to apply to beans defined in the original factory. for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) { if (it.next() instanceof AopInfrastructureBean) { it.remove(); } } }
/** * Invoke {@link ResourceLoaderAware}, {@link BeanClassLoaderAware} and * {@link BeanFactoryAware} contracts if implemented by the given {@code bean}. */ private void invokeAwareMethods(Object importStrategyBean) { if (importStrategyBean instanceof Aware) { if (importStrategyBean instanceof EnvironmentAware) { ((EnvironmentAware) importStrategyBean).setEnvironment(this.environment); } if (importStrategyBean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) importStrategyBean).setResourceLoader(this.resourceLoader); } if (importStrategyBean instanceof BeanClassLoaderAware) { ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ? ((ConfigurableBeanFactory) this.registry).getBeanClassLoader() : this.resourceLoader.getClassLoader()); ((BeanClassLoaderAware) importStrategyBean).setBeanClassLoader(classLoader); } if (importStrategyBean instanceof BeanFactoryAware && this.registry instanceof BeanFactory) { ((BeanFactoryAware) importStrategyBean).setBeanFactory((BeanFactory) this.registry); } } }
/** * Create a subclass proxy that intercepts calls to getObject(), delegating to the current BeanFactory * instead of creating a new instance. These proxies are created only when calling a FactoryBean from * within a Bean method, allowing for proper scoping semantics even when working against the FactoryBean * instance directly. If a FactoryBean instance is fetched through the container via &-dereferencing, * it will not be proxied. This too is aligned with the way XML configuration works. */ private Object enhanceFactoryBean(Class<?> fbClass, final ConfigurableBeanFactory beanFactory, final String beanName) throws InstantiationException, IllegalAccessException { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(fbClass); enhancer.setUseFactory(false); enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.getName().equals("getObject") && args.length == 0) { return beanFactory.getBean(beanName); } return proxy.invokeSuper(obj, args); } }); return enhancer.create(); }
@Override protected Object getResourceToInject(Object target, String requestingBeanName) { if (StringUtils.hasLength(this.beanName)) { if (beanFactory != null && beanFactory.containsBean(this.beanName)) { // Local match found for explicitly specified local bean name. Object bean = beanFactory.getBean(this.beanName, this.lookupType); if (beanFactory instanceof ConfigurableBeanFactory) { ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName); } return bean; } else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) { throw new NoSuchBeanDefinitionException(this.beanName, "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead."); } } // JNDI name lookup - may still go to a local BeanFactory. return getResource(this, requestingBeanName); }
@Override public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { return (beanInstance instanceof FactoryBean); } else if (containsSingleton(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); } return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); }
/** * Subclasses should call this method to destroy an obsolete prototype instance. * @param target the bean instance to destroy */ protected void destroyPrototypeInstance(Object target) { if (this.logger.isDebugEnabled()) { this.logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'"); } if (getBeanFactory() instanceof ConfigurableBeanFactory) { ((ConfigurableBeanFactory) getBeanFactory()).destroyBean(getTargetBeanName(), target); } else if (target instanceof DisposableBean) { try { ((DisposableBean) target).destroy(); } catch (Throwable ex) { logger.error("Couldn't invoke destroy method of bean with name '" + getTargetBeanName() + "'", ex); } } }
/** * Build an internal BeanFactory for resolving target beans. * @param containingFactory the containing BeanFactory that originally defines the beans * @return an independent internal BeanFactory to hold copies of some target beans */ protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) { // Set parent so that references (up container hierarchies) are correctly resolved. DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory); // Required so that all BeanPostProcessors, Scopes, etc become available. internalBeanFactory.copyConfigurationFrom(containingFactory); // Filter out BeanPostProcessors that are part of the AOP infrastructure, // since those are only meant to apply to beans defined in the original factory. for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) { if (it.next() instanceof AopInfrastructureBean) { it.remove(); } } return internalBeanFactory; }
/** * Find a single default EntityManagerFactory in the Spring application context. * @return the default EntityManagerFactory * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context */ protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName) throws NoSuchBeanDefinitionException { String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class); if (beanNames.length == 1) { String unitName = beanNames[0]; EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName); if (this.beanFactory instanceof ConfigurableBeanFactory) { ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName); } return emf; } else if (beanNames.length > 1) { throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames); } else { throw new NoSuchBeanDefinitionException(EntityManagerFactory.class); } }
@Override public void afterPropertiesSet() throws Exception { RequestMappingHandlerAdapter requestMappingHandlerAdapter = this.beanFactory.getBean(RequestMappingHandlerAdapter.class); List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<>(); if (beanFactory instanceof ConfigurableBeanFactory) { argumentResolvers.add(new WxArgumentResolver((ConfigurableBeanFactory) beanFactory)); } else { argumentResolvers.add(new WxArgumentResolver(beanFactory.getBean(WxUserManager.class), beanFactory.getBean(WxUserProvider.class))); } returnValueHandlers.add(beanFactory.getBean(WxAsyncMessageReturnValueHandler.class)); argumentResolvers.addAll(requestMappingHandlerAdapter.getArgumentResolvers()); returnValueHandlers.addAll(requestMappingHandlerAdapter.getReturnValueHandlers()); requestMappingHandlerAdapter.setArgumentResolvers(argumentResolvers); requestMappingHandlerAdapter.setReturnValueHandlers(returnValueHandlers); }
protected List<HandlerMethodArgumentResolver> initArgumentResolvers() { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>(); ConfigurableBeanFactory cbf = (this.beanFactory instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) this.beanFactory : null); // Annotation-based argument resolution resolvers.add(new HeaderMethodArgumentResolver(this.conversionService, cbf)); resolvers.add(new HeadersMethodArgumentResolver()); // Type-based argument resolution resolvers.add(new MessageMethodArgumentResolver()); if (this.customArgumentResolvers != null) { resolvers.addAll(this.customArgumentResolvers); } resolvers.add(new PayloadArgumentResolver(this.messageConverter, this.validator)); return resolvers; }
/** * Invoke {@link ResourceLoaderAware}, {@link BeanClassLoaderAware} and * {@link BeanFactoryAware} contracts if implemented by the given {@code filter}. */ private void invokeAwareMethods(TypeFilter filter) { if (filter instanceof Aware) { if (filter instanceof EnvironmentAware) { ((EnvironmentAware) filter).setEnvironment(this.environment); } if (filter instanceof ResourceLoaderAware) { ((ResourceLoaderAware) filter).setResourceLoader(this.resourceLoader); } if (filter instanceof BeanClassLoaderAware) { ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ? ((ConfigurableBeanFactory) this.registry).getBeanClassLoader() : this.resourceLoader.getClassLoader()); ((BeanClassLoaderAware) filter).setBeanClassLoader(classLoader); } if (filter instanceof BeanFactoryAware && this.registry instanceof BeanFactory) { ((BeanFactoryAware) filter).setBeanFactory((BeanFactory) this.registry); } } }
@Test public void testInitSecurityAwarePrototypeBean() { final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); BeanDefinitionBuilder bdb = BeanDefinitionBuilder .genericBeanDefinition(NonPrivilegedBean.class).setScope( ConfigurableBeanFactory.SCOPE_PROTOTYPE) .setInitMethodName("init").setDestroyMethodName("destroy") .addConstructorArgValue("user1"); lbf.registerBeanDefinition("test", bdb.getBeanDefinition()); final Subject subject = new Subject(); subject.getPrincipals().add(new TestPrincipal("user1")); NonPrivilegedBean bean = Subject.doAsPrivileged( subject, new PrivilegedAction<NonPrivilegedBean>() { @Override public NonPrivilegedBean run() { return lbf.getBean("test", NonPrivilegedBean.class); } }, null); assertNotNull(bean); }
@Test public void aliasing() { BeanFactory bf = getBeanFactory(); if (!(bf instanceof ConfigurableBeanFactory)) { return; } ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf; String alias = "rods alias"; try { cbf.getBean(alias); fail("Shouldn't permit factory get on normal bean"); } catch (NoSuchBeanDefinitionException ex) { // Ok assertTrue(alias.equals(ex.getBeanName())); } // Create alias cbf.registerAlias("rod", alias); Object rod = getBeanFactory().getBean("rod"); Object aliasRod = getBeanFactory().getBean(alias); assertTrue(rod == aliasRod); }
private <T> Supplier<T> createHandlerBeanSupplier(final T h, final Class<? extends T> handlerClass, final String beanName) { final ChannelHandler.Sharable sharable = findAnnotation(handlerClass, ChannelHandler.Sharable.class); if (sharable == null) { final Scope scope = findAnnotation(handlerClass, Scope.class); if ((scope == null) || !ConfigurableBeanFactory.SCOPE_PROTOTYPE.equals(scope.value())) { throw new IllegalStateException("Non-sharable handler should be presented by a " + "prototype bean"); } } return (sharable == null) ? () -> beanFactory.getBean(beanName, handlerClass) : () -> h; }
@Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (!(beanFactory instanceof ConfigurableBeanFactory)) { throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory); } this.beanFactory = (ConfigurableBeanFactory) beanFactory; }
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Bean(name = "verifier-context", initMethod = "start", destroyMethod = "stop") public static CamelContext verifierContext() { CamelContext context = new DefaultCamelContext(); context.setNameStrategy(new ExplicitCamelContextNameStrategy("verifier-context")); context.disableJMX(); return context; }
@Bean("twitter") @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Lazy @ConditionalOnProperty(prefix = "io.syndesis.connector.twitter.verifier", name = "enabled", matchIfMissing = true) public Verifier twitterVerifier() { return new TwitterVerifier(); }
public SpringParameterProvider(ConfigurableBeanFactory beanFactory, HttpServletRequest request) { this.request = request; this.beanFactory = beanFactory; List<HttpMessageConverter<?>> messageConverters = getHttpMessageConverters(); argumentResolvers = new HandlerMethodArgumentResolverComposite() .addResolvers(getArgumentResolvers(messageConverters)); }
@Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @ConditionalOnBean(SqlSession.class) @ConditionalOnMissingBean public SqlMapper sqlMapper(SqlSession sqlSession) { return new SqlMapper(sqlSession); }
private AccessControlContext getAcc() { AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory(); if (beanFactory instanceof ConfigurableBeanFactory) { return ((ConfigurableBeanFactory) beanFactory).getAccessControlContext(); } return null; }
private void createEmbeddedBeanFactory() { synchronized (monitor) { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(owningBeanFactory); if (owningBeanFactory instanceof ConfigurableBeanFactory) { bf.copyConfigurationFrom((ConfigurableBeanFactory) owningBeanFactory); } // just to be on the safe side bf.setBeanClassLoader(classLoader); // add autowiring processor bf.addBeanPostProcessor(new InitialInjectionProcessor()); beanFactory = bf; } }
public static AccessControlContext getAccFrom(BeanFactory beanFactory) { AccessControlContext acc = null; if (beanFactory != null) { if (beanFactory instanceof ConfigurableBeanFactory) { return ((ConfigurableBeanFactory) beanFactory).getAccessControlContext(); } } return acc; }
private void addBeanFactoryDependency() { if (beanFactory instanceof ConfigurableBeanFactory) { ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory; if (StringUtils.hasText(beanName) && cbf.containsBean(beanName)) { // no need to validate targetBeanName (already did) cbf.registerDependentBean(targetBeanName, BeanFactory.FACTORY_BEAN_PREFIX + beanName); cbf.registerDependentBean(targetBeanName, beanName); } } else { log.warn("The running bean factory cannot support dependencies between beans " + "- importer/exporter dependency cannot be enforced"); } }
protected void setUp() throws Exception { exporter = new OsgiServiceFactoryBean(); beanFactoryControl = createControl(); beanFactory = this.beanFactoryControl.createMock(ConfigurableBeanFactory.class); bundleContext = new MockBundleContext(); ctxCtrl = createControl(); ctx = ctxCtrl.createMock(BundleContext.class); exporter.setBeanFactory(beanFactory); exporter.setBundleContext(bundleContext); }
private ConfigurableBeanFactory createMockBF(Object target) { ConfigurableBeanFactory cbf = createNiceMock(ConfigurableBeanFactory.class); expect(cbf.getBean(BEAN_NAME)).andReturn(target); expect(cbf.getType(BEAN_NAME)).andReturn((Class)target.getClass()); replay(cbf); return cbf; }