类org.springframework.beans.factory.BeanFactory源码实例Demo

下面列出了怎么用org.springframework.beans.factory.BeanFactory的API类实例代码及写法,或者点击链接到github查看源代码。

@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();
}
 
@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);
}
 
/**
 * 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;
}
 
@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);
}
 
源代码5 项目: webanno   文件: ExportedComponentPostProcessor.java
private ConfigurableListableBeanFactory getParentBeanFactory()
{
    BeanFactory parent = beanFactory.getParentBeanFactory();

    return (parent instanceof ConfigurableListableBeanFactory)
            ? (ConfigurableListableBeanFactory) parent
            : null;
}
 
@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);
	}
}
 
源代码7 项目: lams   文件: AsyncAnnotationBeanPostProcessor.java
@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;
}
 
源代码8 项目: rice   文件: CompositeBeanFactory.java
@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;
}
 
/**
 * 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);
}
 
源代码10 项目: learnjavabug   文件: SpringUtil.java
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());
}
 
/**
 * 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;
}
 
@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;
}
 
源代码13 项目: lams   文件: AsyncExecutionAspectSupport.java
/**
 * 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);
}
 
/**
 * 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;
}
 
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
	if (beanFactory instanceof ConfigurableBeanFactory) {
		Object typeConverter = ((ConfigurableBeanFactory) beanFactory).getTypeConverter();
		if (typeConverter instanceof SimpleTypeConverter) {
			delegate = (SimpleTypeConverter) typeConverter;
		}
	}
}
 
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);
}
 
@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);
}
 
/**
 * 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()));
	}
}
 
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
	BeanFactory bf = getBeanFactory();
	if (!(bf instanceof ListableBeanFactory)) {
		throw new IllegalStateException("ListableBeanFactory required");
	}
	return (ListableBeanFactory) bf;
}
 
@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()));
}
 
/**
 * 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();
	}
}
 
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	super.setBeanFactory(beanFactory);
	if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
		throw new IllegalArgumentException(
				"AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
	}
	initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
}
 
/**
 * 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;
}
 
/**
 * 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()));
	}
}
 
@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));
}
 
/**
 * 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();
	}
}
 
源代码27 项目: learnjavabug   文件: SpringUtil.java
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;
}
 
源代码28 项目: scriptella-etl   文件: EtlExecutorBean.java
/**
 * 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;
}
 
/**
 * 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));
}
 
源代码30 项目: lams   文件: SpringBeanELResolver.java
@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;
}
 
 同包方法