org.springframework.beans.factory.BeanFactory Java Examples
The following examples show how to use
org.springframework.beans.factory.BeanFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InjectAnnotationBeanPostProcessorTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testExtendedResourceInjectionWithOverriding() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerResolvableDependency(BeanFactory.class, bf); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); RootBeanDefinition annotatedBd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class); TestBean tb2 = new TestBean(); annotatedBd.getPropertyValues().add("testBean2", tb2); bf.registerBeanDefinition("annotatedBean", annotatedBd); TestBean tb = new TestBean(); bf.registerSingleton("testBean", tb); NestedTestBean ntb = new NestedTestBean(); bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); assertSame(tb, bean.getTestBean()); assertSame(tb2, bean.getTestBean2()); assertSame(tb, bean.getTestBean3()); assertSame(tb, bean.getTestBean4()); assertSame(ntb, bean.getNestedTestBean()); assertSame(bf, bean.getBeanFactory()); bf.destroySingletons(); }
Example #2
Source File: AbstractBeanFactoryTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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); }
Example #3
Source File: NettyEmbeddedAutoConfiguration.java From spring-boot-protocol with Apache License 2.0 | 6 votes |
/** * Add a TCP service factory * @param protocolHandlers protocolHandlers * @param serverListeners serverListeners * @param beanFactory beanFactory * @return NettyTcpServerFactory */ @Bean("nettyServerFactory") @ConditionalOnMissingBean(NettyTcpServerFactory.class) public NettyTcpServerFactory nettyTcpServerFactory(Collection<ProtocolHandler> protocolHandlers, Collection<ServerListener> serverListeners, BeanFactory beanFactory){ Supplier<DynamicProtocolChannelHandler> handlerSupplier = ()->{ Class<?extends DynamicProtocolChannelHandler> type = nettyProperties.getChannelHandler(); return type == DynamicProtocolChannelHandler.class? new DynamicProtocolChannelHandler() : beanFactory.getBean(type); }; NettyTcpServerFactory tcpServerFactory = new NettyTcpServerFactory(nettyProperties,handlerSupplier); tcpServerFactory.getProtocolHandlers().addAll(protocolHandlers); tcpServerFactory.getServerListeners().addAll(serverListeners); return tcpServerFactory; }
Example #4
Source File: AbstractBeanFactoryTests.java From java-technology-stack with MIT License | 6 votes |
@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); }
Example #5
Source File: ExportedComponentPostProcessor.java From webanno with Apache License 2.0 | 5 votes |
private ConfigurableListableBeanFactory getParentBeanFactory() { BeanFactory parent = beanFactory.getParentBeanFactory(); return (parent instanceof ConfigurableListableBeanFactory) ? (ConfigurableListableBeanFactory) parent : null; }
Example #6
Source File: SimpleInstantiationStrategy.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (bd.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (bd.constructorArgumentLock) { constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class<?> clazz = bd.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() { @Override public Constructor<?> run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } bd.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. return instantiateWithMethodInjection(bd, beanName, owner); } }
Example #7
Source File: AsyncAnnotationBeanPostProcessor.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void setBeanFactory(BeanFactory beanFactory) { super.setBeanFactory(beanFactory); AsyncAnnotationAdvisor advisor = new AsyncAnnotationAdvisor(this.executor, this.exceptionHandler); if (this.asyncAnnotationType != null) { advisor.setAsyncAnnotationType(this.asyncAnnotationType); } advisor.setBeanFactory(beanFactory); this.advisor = advisor; }
Example #8
Source File: CompositeBeanFactory.java From rice with Educational Community License v2.0 | 5 votes |
@Override public boolean containsBean(String name) { for (BeanFactory f : factories) { try { boolean b = f.containsBean(name); if (b) { return b; } } catch (BeansException e) { LOG.info("bean exception", e); } } return false; }
Example #9
Source File: BeanFactoryAspectInstanceFactory.java From spring-analysis-note with MIT License | 5 votes |
/** * Create a BeanFactoryAspectInstanceFactory, providing a type that AspectJ should * introspect to create AJType metadata. Use if the BeanFactory may consider the type * to be a subclass (as when using CGLIB), and the information should relate to a superclass. * @param beanFactory the BeanFactory to obtain instance(s) from * @param name the name of the bean * @param type the type that should be introspected by AspectJ * ({@code null} indicates resolution through {@link BeanFactory#getType} via the bean name) */ public BeanFactoryAspectInstanceFactory(BeanFactory beanFactory, String name, @Nullable Class<?> type) { Assert.notNull(beanFactory, "BeanFactory must not be null"); Assert.notNull(name, "Bean name must not be null"); this.beanFactory = beanFactory; this.name = name; Class<?> resolvedType = type; if (type == null) { resolvedType = beanFactory.getType(name); Assert.notNull(resolvedType, "Unresolvable bean type - explicitly specify the aspect class"); } this.aspectMetadata = new AspectMetadata(resolvedType, name); }
Example #10
Source File: SpringUtil.java From learnjavabug with MIT License | 5 votes |
public static Object makeBeanFactoryTriggerBFPA(String name, BeanFactory bf) throws Exception { DefaultBeanFactoryPointcutAdvisor pcadv = new DefaultBeanFactoryPointcutAdvisor(); pcadv.setBeanFactory(bf); pcadv.setAdviceBeanName(name); return JDKUtil.makeMap(pcadv, new DefaultBeanFactoryPointcutAdvisor()); }
Example #11
Source File: RefreshableScriptTargetSource.java From java-technology-stack with MIT License | 5 votes |
/** * Create a new RefreshableScriptTargetSource. * @param beanFactory the BeanFactory to fetch the scripted bean from * @param beanName the name of the target bean * @param scriptFactory the ScriptFactory to delegate to for determining * whether a refresh is required * @param scriptSource the ScriptSource for the script definition * @param isFactoryBean whether the target script defines a FactoryBean */ public RefreshableScriptTargetSource(BeanFactory beanFactory, String beanName, ScriptFactory scriptFactory, ScriptSource scriptSource, boolean isFactoryBean) { super(beanFactory, beanName); Assert.notNull(scriptFactory, "ScriptFactory must not be null"); Assert.notNull(scriptSource, "ScriptSource must not be null"); this.scriptFactory = scriptFactory; this.scriptSource = scriptSource; this.isFactoryBean = isFactoryBean; }
Example #12
Source File: AbstractBeanFactory.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void setParentBeanFactory(BeanFactory parentBeanFactory) { if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) { throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory); } this.parentBeanFactory = parentBeanFactory; }
Example #13
Source File: AsyncExecutionAspectSupport.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Retrieve a target executor for the given qualifier. * @param qualifier the qualifier to resolve * @return the target executor, or {@code null} if none available * @since 4.2.6 * @see #getExecutorQualifier(Method) */ protected Executor findQualifiedExecutor(BeanFactory beanFactory, String qualifier) { if (beanFactory == null) { throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() + " to access qualified executor '" + qualifier + "'"); } return BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, Executor.class, qualifier); }
Example #14
Source File: AbstractBeanFactoryBasedTargetSource.java From spring-analysis-note with MIT License | 5 votes |
/** * Set the owning BeanFactory. We need to save a reference so that we can * use the {@code getBean} method on every invocation. */ @Override public void setBeanFactory(BeanFactory beanFactory) { if (this.targetBeanName == null) { throw new IllegalStateException("Property 'targetBeanName' is required"); } this.beanFactory = beanFactory; }
Example #15
Source File: BeanFactoryTypeConverter.java From spring-analysis-note with MIT License | 5 votes |
@Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof ConfigurableBeanFactory) { Object typeConverter = ((ConfigurableBeanFactory) beanFactory).getTypeConverter(); if (typeConverter instanceof SimpleTypeConverter) { delegate = (SimpleTypeConverter) typeConverter; } } }
Example #16
Source File: LazyTraceScheduledThreadPoolExecutor.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
LazyTraceScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, BeanFactory beanFactory, ScheduledThreadPoolExecutor delegate) { super(corePoolSize, threadFactory); this.beanFactory = beanFactory; this.delegate = delegate; this.decorateTaskRunnable = ReflectionUtils.findMethod( ScheduledThreadPoolExecutor.class, "decorateTask", Runnable.class, RunnableScheduledFuture.class); makeAccessibleIfNotNull(this.decorateTaskRunnable); this.decorateTaskCallable = ReflectionUtils.findMethod( ScheduledThreadPoolExecutor.class, "decorateTaskCallable", Callable.class, RunnableScheduledFuture.class); makeAccessibleIfNotNull(this.decorateTaskCallable); this.finalize = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "finalize"); makeAccessibleIfNotNull(this.finalize); this.beforeExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "beforeExecute"); makeAccessibleIfNotNull(this.beforeExecute); this.afterExecute = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "afterExecute", null); makeAccessibleIfNotNull(this.afterExecute); this.terminated = ReflectionUtils.findMethod(ScheduledThreadPoolExecutor.class, "terminated", null); makeAccessibleIfNotNull(this.terminated); this.newTaskForRunnable = ReflectionUtils.findMethod( ScheduledThreadPoolExecutor.class, "newTaskFor", Runnable.class, Object.class); makeAccessibleIfNotNull(this.newTaskForRunnable); this.newTaskForCallable = ReflectionUtils.findMethod( ScheduledThreadPoolExecutor.class, "newTaskFor", Callable.class, Object.class); makeAccessibleIfNotNull(this.newTaskForCallable); }
Example #17
Source File: ProviderCreatingFactoryBean.java From spring-analysis-note with MIT License | 5 votes |
@Override protected Provider<Object> createInstance() { BeanFactory beanFactory = getBeanFactory(); Assert.state(beanFactory != null, "No BeanFactory available"); Assert.state(this.targetBeanName != null, "No target bean name specified"); return new TargetBeanProvider(beanFactory, this.targetBeanName); }
Example #18
Source File: JpaTransactionManager.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Retrieves an EntityManagerFactory by persistence unit name, if none set explicitly. * Falls back to a default EntityManagerFactory bean if no persistence unit specified. * @see #setPersistenceUnitName */ @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (getEntityManagerFactory() == null) { if (!(beanFactory instanceof ListableBeanFactory)) { throw new IllegalStateException("Cannot retrieve EntityManagerFactory by persistence unit name " + "in a non-listable BeanFactory: " + beanFactory); } ListableBeanFactory lbf = (ListableBeanFactory) beanFactory; setEntityManagerFactory(EntityManagerFactoryUtils.findEntityManagerFactory(lbf, getPersistenceUnitName())); } }
Example #19
Source File: AbstractListableBeanFactoryTests.java From spring-analysis-note with MIT License | 5 votes |
/** Subclasses must initialize this */ protected ListableBeanFactory getListableBeanFactory() { BeanFactory bf = getBeanFactory(); if (!(bf instanceof ListableBeanFactory)) { throw new IllegalStateException("ListableBeanFactory required"); } return (ListableBeanFactory) bf; }
Example #20
Source File: ImportBeanDefinitionRegistrarTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void shouldInvokeAwareMethodsInImportBeanDefinitionRegistrar() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); context.getBean(MessageSource.class); assertThat(SampleRegistrar.beanFactory, is((BeanFactory) context.getBeanFactory())); assertThat(SampleRegistrar.classLoader, is(context.getBeanFactory().getBeanClassLoader())); assertThat(SampleRegistrar.resourceLoader, is(notNullValue())); assertThat(SampleRegistrar.environment, is((Environment) context.getEnvironment())); }
Example #21
Source File: JmsListenerEndpointRegistrar.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * A {@link BeanFactory} only needs to be available in conjunction with * {@link #setContainerFactoryBeanName}. */ @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (beanFactory instanceof ConfigurableBeanFactory) { ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory; this.mutex = cbf.getSingletonMutex(); } }
Example #22
Source File: AbstractAdvisorAutoProxyCreator.java From spring-analysis-note with MIT License | 5 votes |
@Override public void setBeanFactory(BeanFactory beanFactory) { super.setBeanFactory(beanFactory); if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( "AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory); } initBeanFactory((ConfigurableListableBeanFactory) beanFactory); }
Example #23
Source File: BeanNameAutoProxyCreator.java From spring-analysis-note with MIT License | 5 votes |
/** * Identify as bean to proxy if the bean name is in the configured list of names. */ @Override @Nullable protected Object[] getAdvicesAndAdvisorsForBean( Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) { if (this.beanNames != null) { for (String mappedName : this.beanNames) { if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { continue; } mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length()); } if (isMatch(beanName, mappedName)) { return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; } BeanFactory beanFactory = getBeanFactory(); if (beanFactory != null) { String[] aliases = beanFactory.getAliases(beanName); for (String alias : aliases) { if (isMatch(alias, mappedName)) { return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; } } } } } return DO_NOT_PROXY; }
Example #24
Source File: EntityManagerFactoryAccessor.java From java-technology-stack with MIT License | 5 votes |
/** * Retrieves an EntityManagerFactory by persistence unit name, if none set explicitly. * Falls back to a default EntityManagerFactory bean if no persistence unit specified. * @see #setPersistenceUnitName */ @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (getEntityManagerFactory() == null) { if (!(beanFactory instanceof ListableBeanFactory)) { throw new IllegalStateException("Cannot retrieve EntityManagerFactory by persistence unit name " + "in a non-listable BeanFactory: " + beanFactory); } ListableBeanFactory lbf = (ListableBeanFactory) beanFactory; setEntityManagerFactory(EntityManagerFactoryUtils.findEntityManagerFactory(lbf, getPersistenceUnitName())); } }
Example #25
Source File: TransactionInterceptorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void determineTransactionManagerWithEmptyQualifierAndDefaultName() { BeanFactory beanFactory = mock(BeanFactory.class); PlatformTransactionManager defaultTransactionManager = associateTransactionManager(beanFactory, "defaultTransactionManager"); TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName( "defaultTransactionManager", beanFactory); DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); attribute.setQualifier(""); assertSame(defaultTransactionManager, ti.determineTransactionManager(attribute)); }
Example #26
Source File: BeanConfigurerSupport.java From spring-analysis-note with MIT License | 5 votes |
/** * Set the {@link BeanFactory} in which this aspect must configure beans. */ @Override public void setBeanFactory(BeanFactory beanFactory) { if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( "Bean configurer aspect needs to run in a ConfigurableListableBeanFactory: " + beanFactory); } this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; if (this.beanWiringInfoResolver == null) { this.beanWiringInfoResolver = createDefaultBeanWiringInfoResolver(); } }
Example #27
Source File: SpringUtil.java From learnjavabug with MIT License | 5 votes |
public static BeanFactory makeJNDITrigger(String jndiUrl) throws Exception { SimpleJndiBeanFactory bf = new SimpleJndiBeanFactory(); bf.setShareableResources(jndiUrl); Reflections.setFieldValue(bf, "logger", new NoOpLog()); Reflections.setFieldValue(bf.getJndiTemplate(), "logger", new NoOpLog()); return bf; }
Example #28
Source File: EtlExecutorBean.java From scriptella-etl with Apache License 2.0 | 5 votes |
/** * Return the bean factory associated with the current thread. * @return bean factory associated with the current thread. */ static synchronized BeanFactory getContextBeanFactory() { ThreadLocal threadLocal = getGlobalThreadLocal(); BeanFactory f = (BeanFactory) threadLocal.get(); if (f == null) { throw new IllegalStateException("No beanfactory associated with the current thread"); } return f; }
Example #29
Source File: DefaultListableBeanFactory.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Return whether the bean definition for the given bean name has been * marked as a primary bean. * @param beanName the name of the bean * @param beanInstance the corresponding bean instance (can be null) * @return whether the given bean qualifies as primary */ protected boolean isPrimary(String beanName, Object beanInstance) { if (containsBeanDefinition(beanName)) { return getMergedLocalBeanDefinition(beanName).isPrimary(); } BeanFactory parentFactory = getParentBeanFactory(); return (parentFactory instanceof DefaultListableBeanFactory && ((DefaultListableBeanFactory) parentFactory).isPrimary(beanName, beanInstance)); }
Example #30
Source File: SpringBeanELResolver.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public boolean isReadOnly(ELContext elContext, Object base, Object property) throws ELException { if (base == null) { String beanName = property.toString(); BeanFactory bf = getBeanFactory(elContext); if (bf.containsBean(beanName)) { return true; } } return false; }