Java Code Examples for org.springframework.beans.factory.BeanFactory

The following examples show how to use org.springframework.beans.factory.BeanFactory. These examples are extracted from open source projects. 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
@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
@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
/**
 * 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 Project: java-technology-stack   Source File: AbstractBeanFactoryTests.java    License: MIT License 6 votes vote down vote up
@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 Project: webanno   Source File: ExportedComponentPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private ConfigurableListableBeanFactory getParentBeanFactory()
{
    BeanFactory parent = beanFactory.getParentBeanFactory();

    return (parent instanceof ConfigurableListableBeanFactory)
            ? (ConfigurableListableBeanFactory) parent
            : null;
}
 
Example 6
@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
@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 Project: rice   Source File: CompositeBeanFactory.java    License: Educational Community License v2.0 5 votes vote down vote up
@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
/**
 * 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 Project: learnjavabug   Source File: SpringUtil.java    License: MIT License 5 votes vote down vote up
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
/**
 * 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 Project: spring4-understanding   Source File: AbstractBeanFactory.java    License: Apache License 2.0 5 votes vote down vote up
@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
/**
 * 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
/**
 * 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 Project: spring-analysis-note   Source File: BeanFactoryTypeConverter.java    License: MIT License 5 votes vote down vote up
@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
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 Project: spring-analysis-note   Source File: ProviderCreatingFactoryBean.java    License: MIT License 5 votes vote down vote up
@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
/**
 * 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
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
	BeanFactory bf = getBeanFactory();
	if (!(bf instanceof ListableBeanFactory)) {
		throw new IllegalStateException("ListableBeanFactory required");
	}
	return (ListableBeanFactory) bf;
}
 
Example 20
@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
/**
 * 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
@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 Project: spring-analysis-note   Source File: BeanNameAutoProxyCreator.java    License: MIT License 5 votes vote down vote up
/**
 * 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
/**
 * 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
@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 Project: spring-analysis-note   Source File: BeanConfigurerSupport.java    License: MIT License 5 votes vote down vote up
/**
 * 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 Project: learnjavabug   Source File: SpringUtil.java    License: MIT License 5 votes vote down vote up
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 Project: scriptella-etl   Source File: EtlExecutorBean.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
/**
 * 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 Project: lams   Source File: SpringBeanELResolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
}