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: NettyEmbeddedAutoConfiguration.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: AbstractBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 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 #3
Source File: InjectAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: AbstractBeanFactoryTests.java    From java-technology-stack with 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 File: ProviderCreatingFactoryBean.java    From spring-analysis-note with 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 #6
Source File: BeanNameAutoProxyCreator.java    From spring-analysis-note with 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 #7
Source File: AbstractAdvisorAutoProxyCreator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #8
Source File: ImportBeanDefinitionRegistrarTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: AbstractListableBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
	BeanFactory bf = getBeanFactory();
	if (!(bf instanceof ListableBeanFactory)) {
		throw new IllegalStateException("ListableBeanFactory required");
	}
	return (ListableBeanFactory) bf;
}
 
Example #10
Source File: JpaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #11
Source File: TransactionInterceptorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: LazyTraceScheduledThreadPoolExecutor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: BeanFactoryTypeConverter.java    From spring-analysis-note with 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 #14
Source File: AbstractBeanFactoryBasedTargetSource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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: RefreshableScriptTargetSource.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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 #16
Source File: AbstractBeanFactory.java    From spring4-understanding with 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 #17
Source File: ExportedComponentPostProcessor.java    From webanno with 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 #18
Source File: EntityManagerFactoryAccessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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: JmsListenerEndpointRegistrar.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #20
Source File: BeanConfigurerSupport.java    From spring-analysis-note with 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 #21
Source File: SpringUtil.java    From learnjavabug with 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 #22
Source File: EtlExecutorBean.java    From scriptella-etl with 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 #23
Source File: DefaultListableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: SpringBeanELResolver.java    From lams with 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;
}
 
Example #25
Source File: ConfigurationClassProcessingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void configWithObjectReturnType() {
	BeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
	assertEquals(Object.class, factory.getType("stringBean"));
	assertFalse(factory.isTypeMatch("stringBean", String.class));
	String stringBean = factory.getBean("stringBean", String.class);
	assertEquals("foo", stringBean);
}
 
Example #26
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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) {
	String transformedBeanName = transformedBeanName(beanName);
	if (containsBeanDefinition(transformedBeanName)) {
		return getMergedLocalBeanDefinition(transformedBeanName).isPrimary();
	}
	BeanFactory parent = getParentBeanFactory();
	return (parent instanceof DefaultListableBeanFactory &&
			((DefaultListableBeanFactory) parent).isPrimary(transformedBeanName, beanInstance));
}
 
Example #27
Source File: AdvisorAutoProxyCreatorIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegexpApplied() throws Exception {
	BeanFactory bf = getBeanFactory();
	ITestBean test = (ITestBean) bf.getBean("test");
	MethodCounter counter = (MethodCounter) bf.getBean("countingAdvice");
	assertEquals(0, counter.getCalls());
	test.getName();
	assertEquals(1, counter.getCalls());
}
 
Example #28
Source File: DefaultLazyPropertyFilter.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
public DefaultLazyPropertyFilter(ConfigurableEnvironment e, String customFilterBeanName, boolean isCustom, BeanFactory bf) {
    singleton = new Singleton<>(() ->
            Optional.of(customFilterBeanName)
                    .filter(bf::containsBean)
                    .map(name -> (EncryptablePropertyFilter) bf.getBean(name))
                    .map(tap(bean -> log.info("Found Custom Filter Bean {} with name: {}", bean, customFilterBeanName)))
                    .orElseGet(() -> {
                        if (isCustom) {
                            throw new IllegalStateException(String.format("Property Filter custom Bean not found with name '%s'", customFilterBeanName));
                        }

                        log.info("Property Filter custom Bean not found with name '{}'. Initializing Default Property Filter", customFilterBeanName);
                        return createDefault(e);
                    }));
}
 
Example #29
Source File: AbstractAdvisorAutoProxyCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #30
Source File: TraceableExecutorServiceTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
BeanFactory beanFactory(boolean refreshed) {
	BDDMockito.given(this.beanFactory.getBean(Tracing.class))
			.willReturn(this.tracing);
	BDDMockito.given(this.beanFactory.getBean(SpanNamer.class))
			.willReturn(new DefaultSpanNamer());
	SleuthContextListenerAccessor.set(this.beanFactory, refreshed);
	return this.beanFactory;
}