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

The following are top voted examples for showing how to use org.springframework.beans.factory.FactoryBean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: StaticListableBeanFactory.java   Source Code and License 7 votes vote down vote up
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
	String beanName = BeanFactoryUtils.transformedBeanName(name);

	Object bean = this.beans.get(beanName);
	if (bean == null) {
		throw new NoSuchBeanDefinitionException(beanName,
				"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
	}

	if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
		// If it's a FactoryBean, we want to look at what it creates, not the factory class.
		return ((FactoryBean<?>) bean).getObjectType();
	}
	return bean.getClass();
}
 
Example 2
Project: lams   File: StaticListableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
public String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean includeFactoryBeans) {
	boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
	List<String> matches = new ArrayList<String>();
	for (String name : this.beans.keySet()) {
		Object beanInstance = this.beans.get(name);
		if (beanInstance instanceof FactoryBean && !isFactoryType) {
			if (includeFactoryBeans) {
				Class<?> objectType = ((FactoryBean<?>) beanInstance).getObjectType();
				if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
					matches.add(name);
				}
			}
		}
		else {
			if (type == null || type.isInstance(beanInstance)) {
				matches.add(name);
			}
		}
	}
	return StringUtils.toStringArray(matches);
}
 
Example 3
Project: lams   File: FactoryBeanRegistrySupport.java   Source Code and License 6 votes vote down vote up
/**
 * Determine the type for the given FactoryBean.
 * @param factoryBean the FactoryBean instance to check
 * @return the FactoryBean's object type,
 * or {@code null} if the type cannot be determined yet
 */
protected Class<?> getTypeForFactoryBean(final FactoryBean<?> factoryBean) {
	try {
		if (System.getSecurityManager() != null) {
			return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
				@Override
				public Class<?> run() {
					return factoryBean.getObjectType();
				}
			}, getAccessControlContext());
		}
		else {
			return factoryBean.getObjectType();
		}
	}
	catch (Throwable ex) {
		// Thrown from the FactoryBean's getObjectType implementation.
		logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " +
				"that it should return null if the type of its object cannot be determined yet", ex);
		return null;
	}
}
 
Example 4
Project: lams   File: AbstractBeanFactory.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 5
Project: lams   File: AbstractBeanFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} else
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		// Can only happen when getting a FactoryBean.
		if (logger.isDebugEnabled()) {
			logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex);
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example 6
Project: lams   File: AbstractAutowireCapableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
	Class<?> targetType = mbd.getTargetType();
	if (targetType == null) {
		targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
				resolveBeanClass(mbd, beanName, typesToMatch));
		if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
			mbd.setTargetType(targetType);
		}
	}
	// Apply SmartInstantiationAwareBeanPostProcessors to predict the
	// eventual type after a before-instantiation shortcut.
	if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
				SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
				Class<?> predicted = ibp.predictBeanType(targetType, beanName);
				if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) ||
						FactoryBean.class.isAssignableFrom(predicted))) {
					return predicted;
				}
			}
		}
	}
	return targetType;
}
 
Example 7
Project: lams   File: AbstractAutowireCapableBeanFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Obtain a "shortcut" non-singleton FactoryBean instance to use for a
 * {@code getObjectType()} call, without full initialization
 * of the FactoryBean.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return the FactoryBean instance, or {@code null} to indicate
 * that we couldn't obtain a shortcut FactoryBean instance
 */
private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
	if (isPrototypeCurrentlyInCreation(beanName)) {
		return null;
	}
	Object instance = null;
	try {
		// Mark this bean as currently in creation, even if just partially.
		beforePrototypeCreation(beanName);
		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
		instance = resolveBeforeInstantiation(beanName, mbd);
		if (instance == null) {
			BeanWrapper bw = createBeanInstance(beanName, mbd, null);
			instance = bw.getWrappedInstance();
		}
	}
	finally {
		// Finished partial creation of this bean.
		afterPrototypeCreation(beanName);
	}
	return getFactoryBean(beanName, instance);
}
 
Example 8
Project: lams   File: AspectJExpressionPointcut.java   Source Code and License 6 votes vote down vote up
private FuzzyBoolean contextMatch(Class<?> targetType) {
	String advisedBeanName = getCurrentProxiedBeanName();
	if (advisedBeanName == null) {  // no proxy creation in progress
		// abstain; can't return YES, since that will make pointcut with negation fail
		return FuzzyBoolean.MAYBE;
	}
	if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) {
		return FuzzyBoolean.NO;
	}
	if (targetType != null) {
		boolean isFactory = FactoryBean.class.isAssignableFrom(targetType);
		return FuzzyBoolean.fromBoolean(
				matchesBeanName(isFactory ? BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName : advisedBeanName));
	}
	else {
		return FuzzyBoolean.fromBoolean(matchesBeanName(advisedBeanName) ||
				matchesBeanName(BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName));
	}
}
 
Example 9
Project: holon-datastore-jpa   File: TestBase.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource());
	emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
	emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName());
	emf.setPersistenceUnitName("test");
	return emf;
}
 
Example 10
Project: springmock   File: BeanDefinitionFinderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_resolve_factory_bean_definition() {
	//given
	final String factoryBeanName = "factoryBean";
	final DoubleRegistry doubleRegistry = new DoubleRegistry(
			emptyList(),
			emptyList());
	final ApplicationContext appCtx = buildAppContext(Stream.of(
			bean(factoryBeanName, new AnyFactoryBean())
	));
	final BeanDefinitionFinder definitionFinder = new BeanDefinitionFinder(appCtx, doubleRegistry);

	//when
	Optional<BeanDefinition> definition = definitionFinder.tryToFindBeanDefinition(FACTORY_BEAN_PREFIX + factoryBeanName, FactoryBean.class);

	//then
	assertTrue(definition.isPresent());
}
 
Example 11
Project: springmock   File: ShouldReplaceFactoryBeanWithDoubles.java   Source Code and License 6 votes vote down vote up
@Bean(MOCK)
FactoryBean<Service> notMockFactoryBean() {
	return new FactoryBean<Service>() {
		@Override
		public Service getObject() throws Exception {
			return notMock;
		}

		@Override
		public Class<?> getObjectType() {
			return Service.class;
		}

		@Override
		public boolean isSingleton() {
			return true;
		}
	};
}
 
Example 12
Project: springmock   File: ShouldReplaceFactoryBeanWithDoubles.java   Source Code and License 6 votes vote down vote up
@Bean(SPY)
FactoryBean<Service> notSpyFactoryBean() {
	return new FactoryBean<Service>() {
		@Override
		public Service getObject() throws Exception {
			return notSpy;
		}

		@Override
		public Class<?> getObjectType() {
			return Service.class;
		}

		@Override
		public boolean isSingleton() {
			return true;
		}
	};
}
 
Example 13
Project: spring4-understanding   File: AspectJExpressionPointcut.java   Source Code and License 6 votes vote down vote up
private FuzzyBoolean contextMatch(Class<?> targetType) {
	String advisedBeanName = getCurrentProxiedBeanName();
	if (advisedBeanName == null) {  // no proxy creation in progress
		// abstain; can't return YES, since that will make pointcut with negation fail
		return FuzzyBoolean.MAYBE;
	}
	if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) {
		return FuzzyBoolean.NO;
	}
	if (targetType != null) {
		boolean isFactory = FactoryBean.class.isAssignableFrom(targetType);
		return FuzzyBoolean.fromBoolean(
				matchesBeanName(isFactory ? BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName : advisedBeanName));
	}
	else {
		return FuzzyBoolean.fromBoolean(matchesBeanName(advisedBeanName) ||
				matchesBeanName(BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName));
	}
}
 
Example 14
Project: spring4-understanding   File: ConfigurationClassSpr8954Tests.java   Source Code and License 6 votes vote down vote up
@Test
public void repro() {
	AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext();
	bf.registerBeanDefinition("fooConfig", new RootBeanDefinition(FooConfig.class));
	bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP());
	bf.refresh();

	assertThat(bf.getBean("foo"), instanceOf(Foo.class));
	assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class));

	assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true));

	@SuppressWarnings("rawtypes")
	Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class);
	assertThat(1, equalTo(fbBeans.size()));
	assertThat("&foo", equalTo(fbBeans.keySet().iterator().next()));

	Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class);
	assertThat(1, equalTo(aiBeans.size()));
	assertThat("&foo", equalTo(aiBeans.keySet().iterator().next()));
}
 
Example 15
Project: spring4-understanding   File: ConfigurationClassSpr8954Tests.java   Source Code and License 6 votes vote down vote up
@Test
public void findsBeansByTypeIfNotInstantiated() {
	AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext();
	bf.registerBeanDefinition("fooConfig", new RootBeanDefinition(FooConfig.class));
	bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP());
	bf.refresh();

	assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true));

	@SuppressWarnings("rawtypes")
	Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class);
	assertThat(1, equalTo(fbBeans.size()));
	assertThat("&foo", equalTo(fbBeans.keySet().iterator().next()));

	Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class);
	assertThat(1, equalTo(aiBeans.size()));
	assertThat("&foo", equalTo(aiBeans.keySet().iterator().next()));
}
 
Example 16
Project: spring4-understanding   File: ConfigurationClassProcessingTests.java   Source Code and License 6 votes vote down vote up
@Test
public void configWithFactoryBeanReturnType() {
	ListableBeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
	assertEquals(List.class, factory.getType("factoryBean"));
	assertTrue(factory.isTypeMatch("factoryBean", List.class));
	assertEquals(FactoryBean.class, factory.getType("&factoryBean"));
	assertTrue(factory.isTypeMatch("&factoryBean", FactoryBean.class));
	assertFalse(factory.isTypeMatch("&factoryBean", BeanClassLoaderAware.class));
	assertFalse(factory.isTypeMatch("&factoryBean", ListFactoryBean.class));
	assertTrue(factory.getBean("factoryBean") instanceof List);

	String[] beanNames = factory.getBeanNamesForType(FactoryBean.class);
	assertEquals(1, beanNames.length);
	assertEquals("&factoryBean", beanNames[0]);

	beanNames = factory.getBeanNamesForType(BeanClassLoaderAware.class);
	assertEquals(1, beanNames.length);
	assertEquals("&factoryBean", beanNames[0]);

	beanNames = factory.getBeanNamesForType(ListFactoryBean.class);
	assertEquals(1, beanNames.length);
	assertEquals("&factoryBean", beanNames[0]);

	beanNames = factory.getBeanNamesForType(List.class);
	assertEquals("factoryBean", beanNames[0]);
}
 
Example 17
Project: spring4-understanding   File: PropertySourceAnnotationTests.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean testBean() {
	final String name = env.getProperty("testbean.name");
	return new FactoryBean() {
		@Override
		public Object getObject() {
			return new TestBean(name);
		}
		@Override
		public Class<?> getObjectType() {
			return TestBean.class;
		}
		@Override
		public boolean isSingleton() {
			return false;
		}
	};
}
 
Example 18
Project: spring4-understanding   File: ProxyFactoryBeanTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetObjectTypeWithNoTargetOrTargetSource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(TARGETSOURCE_CONTEXT, CLASS));

	ITestBean tb = (ITestBean) bf.getBean("noTarget");
	try {
		tb.getName();
		fail();
	}
	catch (UnsupportedOperationException ex) {
		assertEquals("getName", ex.getMessage());
	}
	FactoryBean<?> pfb = (ProxyFactoryBean) bf.getBean("&noTarget");
	assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(pfb.getObjectType()));
}
 
Example 19
Project: spring4-understanding   File: AutoProxyCreatorTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAutoProxyCreatorWithFactoryBean() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);
	sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);
	sac.refresh();

	TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
	tapc.testInterceptor.nrOfInvocations = 0;

	FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(factory));

	TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(tb));
	assertEquals(2, tapc.testInterceptor.nrOfInvocations);
	tb.getAge();
	assertEquals(3, tapc.testInterceptor.nrOfInvocations);
}
 
Example 20
Project: spring4-understanding   File: AutoProxyCreatorTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAutoProxyCreatorWithFactoryBeanAndPrototype() {
	StaticApplicationContext sac = new StaticApplicationContext();
	sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("singleton", "false");
	sac.registerSingleton("prototypeFactoryToBeProxied", DummyFactory.class, pvs);

	sac.refresh();

	TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
	tapc.testInterceptor.nrOfInvocations = 0;

	FactoryBean<?> prototypeFactory = (FactoryBean<?>) sac.getBean("&prototypeFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(prototypeFactory));
	TestBean tb = (TestBean) sac.getBean("prototypeFactoryToBeProxied");
	assertTrue(AopUtils.isCglibProxy(tb));

	assertEquals(2, tapc.testInterceptor.nrOfInvocations);
	tb.getAge();
	assertEquals(3, tapc.testInterceptor.nrOfInvocations);
}
 
Example 21
Project: spring4-understanding   File: StaticListableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
	String beanName = BeanFactoryUtils.transformedBeanName(name);

	Object bean = this.beans.get(beanName);
	if (bean == null) {
		throw new NoSuchBeanDefinitionException(beanName,
				"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
	}

	if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
		// If it's a FactoryBean, we want to look at what it creates, not the factory class.
		return ((FactoryBean<?>) bean).getObjectType();
	}
	return bean.getClass();
}
 
Example 22
Project: spring4-understanding   File: StaticListableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
public String[] getBeanNamesForType(ResolvableType type) {
	boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type.getRawClass()));
	List<String> matches = new ArrayList<String>();
	for (Map.Entry<String, Object> entry : this.beans.entrySet()) {
		String name = entry.getKey();
		Object beanInstance = entry.getValue();
		if (beanInstance instanceof FactoryBean && !isFactoryType) {
			Class<?> objectType = ((FactoryBean<?>) beanInstance).getObjectType();
			if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
				matches.add(name);
			}
		}
		else {
			if (type == null || type.isInstance(beanInstance)) {
				matches.add(name);
			}
		}
	}
	return StringUtils.toStringArray(matches);
}
 
Example 23
Project: spring4-understanding   File: AbstractBeanFactory.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 24
Project: spring4-understanding   File: AbstractBeanFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} else
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		if (ex instanceof BeanCurrentlyInCreationException) {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean currently in creation on FactoryBean type check: " + ex);
			}
		}
		else {
			if (logger.isWarnEnabled()) {
				logger.warn("Bean creation exception on FactoryBean type check: " + ex);
			}
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example 25
Project: spring4-understanding   File: AbstractAutowireCapableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
	Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);

	// Apply SmartInstantiationAwareBeanPostProcessors to predict the
	// eventual type after a before-instantiation shortcut.
	if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
				SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
				Class<?> predicted = ibp.predictBeanType(targetType, beanName);
				if (predicted != null && (typesToMatch.length != 1 || FactoryBean.class != typesToMatch[0] ||
						FactoryBean.class.isAssignableFrom(predicted))) {
					return predicted;
				}
			}
		}
	}
	return targetType;
}
 
Example 26
Project: konker-platform   File: SecurityTestConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<Tenant> tenantFactoryBean() {
    return new FactoryBean<Tenant>() {
        @Override
        public Tenant getObject() throws Exception {
            return Tenant.builder()
                .id("tenant_id")
                .domainName("domainName")
                .name("Konker").build();
        }

        @Override
        public Class<?> getObjectType() {
            return Tenant.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }
    };
}
 
Example 27
Project: konker-platform   File: SecurityTestConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<Tenant> tenantFactoryBean() {
    return new FactoryBean<Tenant>() {
        @Override
        public Tenant getObject() throws Exception {
            return Tenant.builder()
                .id("tenant_id")
                .domainName("domainName")
                .name("Konker").build();
        }

        @Override
        public Class<?> getObjectType() {
            return Tenant.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }
    };
}
 
Example 28
Project: konker-platform   File: SecurityTestConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<Tenant> tenantFactoryBean() {
    return new FactoryBean<Tenant>() {
        @Override
        public Tenant getObject() throws Exception {
            return Tenant.builder()
                .id("tenant_id")
                .domainName("domainName")
                .name("Konker").build();
        }

        @Override
        public Class<?> getObjectType() {
            return Tenant.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }
    };
}
 
Example 29
Project: konker-platform   File: SecurityTestConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<Tenant> tenantFactoryBean() {
    return new FactoryBean<Tenant>() {
        @Override
        public Tenant getObject() throws Exception {
            return Tenant.builder()
                .id("tenant_id")
                .domainName("domainName")
                .name("Konker").build();
        }

        @Override
        public Class<?> getObjectType() {
            return Tenant.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }
    };
}
 
Example 30
Project: konker-platform   File: SecurityTestConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<Tenant> tenantFactoryBean() {
    return new FactoryBean<Tenant>() {
        @Override
        public Tenant getObject() throws Exception {
            return Tenant.builder()
                .id("tenant_id")
                .domainName("domainName")
                .name("Konker").build();
        }

        @Override
        public Class<?> getObjectType() {
            return Tenant.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }
    };
}
 
Example 31
Project: konker-platform   File: SecurityTestConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public FactoryBean<Tenant> tenantFactoryBean() {
    return new FactoryBean<Tenant>() {
        @Override
        public Tenant getObject() throws Exception {
            return Tenant.builder()
                .id("tenant_id")
                .domainName("domainName")
                .name("Konker").build();
        }

        @Override
        public Class<?> getObjectType() {
            return Tenant.class;
        }

        @Override
        public boolean isSingleton() {
            return false;
        }
    };
}
 
Example 32
Project: spring   File: StaticListableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
	String beanName = BeanFactoryUtils.transformedBeanName(name);

	Object bean = this.beans.get(beanName);
	if (bean == null) {
		throw new NoSuchBeanDefinitionException(beanName,
				"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
	}

	if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
		// If it's a FactoryBean, we want to look at what it creates, not the factory class.
		return ((FactoryBean<?>) bean).getObjectType();
	}
	return bean.getClass();
}
 
Example 33
Project: spring   File: StaticListableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
public String[] getBeanNamesForType(ResolvableType type) {
	boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type.getRawClass()));
	List<String> matches = new ArrayList<String>();
	for (Map.Entry<String, Object> entry : this.beans.entrySet()) {
		String name = entry.getKey();
		Object beanInstance = entry.getValue();
		if (beanInstance instanceof FactoryBean && !isFactoryType) {
			Class<?> objectType = ((FactoryBean<?>) beanInstance).getObjectType();
			if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
				matches.add(name);
			}
		}
		else {
			if (type == null || type.isInstance(beanInstance)) {
				matches.add(name);
			}
		}
	}
	return StringUtils.toStringArray(matches);
}
 
Example 34
Project: spring   File: FactoryBeanRegistrySupport.java   Source Code and License 6 votes vote down vote up
/**
 * Determine the type for the given FactoryBean.
 * @param factoryBean the FactoryBean instance to check
 * @return the FactoryBean's object type,
 * or {@code null} if the type cannot be determined yet
 */
protected Class<?> getTypeForFactoryBean(final FactoryBean<?> factoryBean) {
	try {
		if (System.getSecurityManager() != null) {
			return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
				@Override
				public Class<?> run() {
					return factoryBean.getObjectType();
				}
			}, getAccessControlContext());
		}
		else {
			return factoryBean.getObjectType();
		}
	}
	catch (Throwable ex) {
		// Thrown from the FactoryBean's getObjectType implementation.
		logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " +
				"that it should return null if the type of its object cannot be determined yet", ex);
		return null;
	}
}
 
Example 35
Project: spring   File: AbstractBeanFactory.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 36
Project: spring   File: AbstractAutowireCapableBeanFactory.java   Source Code and License 6 votes vote down vote up
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
	Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);

	// Apply SmartInstantiationAwareBeanPostProcessors to predict the
	// eventual type after a before-instantiation shortcut.
	if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
				SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
				Class<?> predicted = ibp.predictBeanType(targetType, beanName);
				if (predicted != null && (typesToMatch.length != 1 || FactoryBean.class != typesToMatch[0] ||
						FactoryBean.class.isAssignableFrom(predicted))) {
					return predicted;
				}
			}
		}
	}
	return targetType;
}
 
Example 37
Project: cas-5.1.0   File: CasCoreHttpConfiguration.java   Source Code and License 5 votes vote down vote up
@ConditionalOnMissingBean(name = "httpClient")
@Bean
public FactoryBean<SimpleHttpClient> httpClient() {
    final SimpleHttpClientFactoryBean.DefaultHttpClient c = new SimpleHttpClientFactoryBean.DefaultHttpClient();
    c.setConnectionTimeout(casProperties.getHttpClient().getConnectionTimeout());
    c.setReadTimeout(Long.valueOf(casProperties.getHttpClient().getReadTimeout()).intValue());
    return c;
}
 
Example 38
Project: vertx-spring   File: VerticleBeanPostProcessor.java   Source Code and License 5 votes vote down vote up
private boolean isVerticleBeanDefinition(String beanName, BeanDefinition beanDefinition) {
    Class<?> beanClass = getBeanClass(beanName, beanDefinition);
    if (beanClass != null) {
        if (Verticle.class.isAssignableFrom(beanClass)) {
            return true;
        }
        if (FactoryBean.class.isAssignableFrom(beanClass) && beanDefinition instanceof AnnotatedBeanDefinition) {
            MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata();
            if (factoryMethodMetadata != null && factoryMethodMetadata.isAnnotated(VerticleDeployment.class.getName())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 39
Project: holon-datastore-jpa-querydsl   File: TestJpaQueryDslDatastoreHibernate.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource());

	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);

	emf.setJpaVendorAdapter(va);

	emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName());
	emf.setPersistenceUnitName("test");
	return emf;
}
 
Example 40
Project: holon-datastore-jpa-querydsl   File: TestJpaQueryDslDatastoreEclipselink.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource());

	emf.setJpaVendorAdapter(new EclipseLinkJpaVendorAdapter());

	emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName());
	emf.setPersistenceUnitName("test");

	emf.getJpaPropertyMap().put("eclipselink.weaving", "false");
	return emf;
}
 
Example 41
Project: lams   File: StaticListableBeanFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Object getBean(String name) throws BeansException {
	String beanName = BeanFactoryUtils.transformedBeanName(name);
	Object bean = this.beans.get(beanName);

	if (bean == null) {
		throw new NoSuchBeanDefinitionException(beanName,
				"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
	}

	// Don't let calling code try to dereference the
	// bean factory if the bean isn't a factory
	if (BeanFactoryUtils.isFactoryDereference(name) && !(bean instanceof FactoryBean)) {
		throw new BeanIsNotAFactoryException(beanName, bean.getClass());
	}

	if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
		try {
			return ((FactoryBean<?>) bean).getObject();
		}
		catch (Exception ex) {
			throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
		}
	}
	else {
		return bean;
	}
}
 
Example 42
Project: lams   File: StaticListableBeanFactory.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
	Object bean = getBean(name);
	// In case of FactoryBean, return prototype status of created object.
	return ((bean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) bean).isPrototype()) ||
			(bean instanceof FactoryBean && !((FactoryBean<?>) bean).isSingleton()));
}
 
Example 43
Project: lams   File: StaticListableBeanFactory.java   Source Code and License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean includeFactoryBeans)
		throws BeansException {

	boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
	Map<String, T> matches = new HashMap<String, T>();

	for (Map.Entry<String, Object> entry : beans.entrySet()) {
		String beanName = entry.getKey();
		Object beanInstance = entry.getValue();
		// Is bean a FactoryBean?
		if (beanInstance instanceof FactoryBean && !isFactoryType) {
			if (includeFactoryBeans) {
				// Match object created by FactoryBean.
				FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
				Class<?> objectType = factory.getObjectType();
				if ((includeNonSingletons || factory.isSingleton()) &&
						objectType != null && (type == null || type.isAssignableFrom(objectType))) {
					matches.put(beanName, getBean(beanName, type));
				}
			}
		}
		else {
			if (type == null || type.isInstance(beanInstance)) {
				// If type to match is FactoryBean, return FactoryBean itself.
				// Else, return bean instance.
				if (isFactoryType) {
					beanName = FACTORY_BEAN_PREFIX + beanName;
				}
				matches.put(beanName, (T) beanInstance);
			}
		}
	}
	return matches;
}
 
Example 44
Project: lams   File: FactoryBeanRegistrySupport.java   Source Code and License 5 votes vote down vote up
/**
 * Get a FactoryBean for the given bean if possible.
 * @param beanName the name of the bean
 * @param beanInstance the corresponding bean instance
 * @return the bean instance as FactoryBean
 * @throws BeansException if the given bean cannot be exposed as a FactoryBean
 */
protected FactoryBean<?> getFactoryBean(String beanName, Object beanInstance) throws BeansException {
	if (!(beanInstance instanceof FactoryBean)) {
		throw new BeanCreationException(beanName,
				"Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean");
	}
	return (FactoryBean<?>) beanInstance;
}
 
Example 45
Project: lams   File: AbstractBeanFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Get the object for the given bean instance, either the bean
 * instance itself or its created object in case of a FactoryBean.
 * @param beanInstance the shared bean instance
 * @param name name that may include factory dereference prefix
 * @param beanName the canonical bean name
 * @param mbd the merged bean definition
 * @return the object to expose for the bean
 */
protected Object getObjectForBeanInstance(
		Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {

	// Don't let calling code try to dereference the factory if the bean isn't a factory.
	if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
		throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
	}

	// Now we have the bean instance, which may be a normal bean or a FactoryBean.
	// If it's a FactoryBean, we use it to create a bean instance, unless the
	// caller actually wants a reference to the factory.
	if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
		return beanInstance;
	}

	Object object = null;
	if (mbd == null) {
		object = getCachedObjectForFactoryBean(beanName);
	}
	if (object == null) {
		// Return bean instance from factory.
		FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
		// Caches object obtained from FactoryBean if it is a singleton.
		if (mbd == null && containsBeanDefinition(beanName)) {
			mbd = getMergedLocalBeanDefinition(beanName);
		}
		boolean synthetic = (mbd != null && mbd.isSynthetic());
		object = getObjectFromFactoryBean(factory, beanName, !synthetic);
	}
	return object;
}
 
Example 46
Project: lams   File: AbstractAutowireCapableBeanFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Obtain a "shortcut" singleton FactoryBean instance to use for a
 * {@code getObjectType()} call, without full initialization
 * of the FactoryBean.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return the FactoryBean instance, or {@code null} to indicate
 * that we couldn't obtain a shortcut FactoryBean instance
 */
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
	synchronized (getSingletonMutex()) {
		BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
		if (bw != null) {
			return (FactoryBean<?>) bw.getWrappedInstance();
		}
		if (isSingletonCurrentlyInCreation(beanName)) {
			return null;
		}
		Object instance = null;
		try {
			// Mark this bean as currently in creation, even if just partially.
			beforeSingletonCreation(beanName);
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			instance = resolveBeforeInstantiation(beanName, mbd);
			if (instance == null) {
				bw = createBeanInstance(beanName, mbd, null);
				instance = bw.getWrappedInstance();
			}
		}
		finally {
			// Finished partial creation of this bean.
			afterSingletonCreation(beanName);
		}
		FactoryBean<?> fb = getFactoryBean(beanName, instance);
		if (bw != null) {
			this.factoryBeanInstanceCache.put(beanName, bw);
		}
		return fb;
	}
}
 
Example 47
Project: lams   File: DefaultListableBeanFactory.java   Source Code and License 5 votes vote down vote up
@Override
public void preInstantiateSingletons() throws BeansException {
	if (this.logger.isDebugEnabled()) {
		this.logger.debug("Pre-instantiating singletons in " + this);
	}
	List<String> beanNames;
	synchronized (this.beanDefinitionMap) {
		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		beanNames = new ArrayList<String>(this.beanDefinitionNames);
	}
	for (String beanName : beanNames) {
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			if (isFactoryBean(beanName)) {
				final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
				boolean isEagerInit;
				if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
					isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
						@Override
						public Boolean run() {
							return ((SmartFactoryBean<?>) factory).isEagerInit();
						}
					}, getAccessControlContext());
				}
				else {
					isEagerInit = (factory instanceof SmartFactoryBean &&
							((SmartFactoryBean<?>) factory).isEagerInit());
				}
				if (isEagerInit) {
					getBean(beanName);
				}
			}
			else {
				getBean(beanName);
			}
		}
	}
}
 
Example 48
Project: lams   File: BeanDefinitionValueResolver.java   Source Code and License 5 votes vote down vote up
/**
 * Resolve an inner bean definition.
 * @param argName the name of the argument that the inner bean is defined for
 * @param innerBeanName the name of the inner bean
 * @param innerBd the bean definition for the inner bean
 * @return the resolved inner bean instance
 */
private Object resolveInnerBean(Object argName, String innerBeanName, BeanDefinition innerBd) {
	RootBeanDefinition mbd = null;
	try {
		mbd = this.beanFactory.getMergedBeanDefinition(innerBeanName, innerBd, this.beanDefinition);
		// Check given bean name whether it is unique. If not already unique,
		// add counter - increasing the counter until the name is unique.
		String actualInnerBeanName = innerBeanName;
		if (mbd.isSingleton()) {
			actualInnerBeanName = adaptInnerBeanName(innerBeanName);
		}
		this.beanFactory.registerContainedBean(actualInnerBeanName, this.beanName);
		// Guarantee initialization of beans that the inner bean depends on.
		String[] dependsOn = mbd.getDependsOn();
		if (dependsOn != null) {
			for (String dependsOnBean : dependsOn) {
				this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName);
				this.beanFactory.getBean(dependsOnBean);
			}
		}
		// Actually create the inner bean instance now...
		Object innerBean = this.beanFactory.createBean(actualInnerBeanName, mbd, null);
		if (innerBean instanceof FactoryBean) {
			boolean synthetic = mbd.isSynthetic();
			return this.beanFactory.getObjectFromFactoryBean(
					(FactoryBean<?>) innerBean, actualInnerBeanName, !synthetic);
		}
		else {
			return innerBean;
		}
	}
	catch (BeansException ex) {
		throw new BeanCreationException(
				this.beanDefinition.getResourceDescription(), this.beanName,
				"Cannot create inner bean '" + innerBeanName + "' " +
				(mbd != null && mbd.getBeanClassName() != null ? "of type [" + mbd.getBeanClassName() + "] " : "") +
				"while setting " + argName, ex);
	}
}
 
Example 49
Project: lams   File: BeanNameAutoProxyCreator.java   Source Code and License 5 votes vote down vote up
/**
 * Identify as bean to proxy if the bean name is in the configured list of names.
 */
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, 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 50
Project: spring-i18n-support   File: JpaMessageSourceDaoTest.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
	factory.setDataSource(dataSource());
	factory.setJpaVendorAdapter(jpaVendorAdapter());
	factory.setPackagesToScan("com.namics.oss.spring.support.i18n.dao.jpa");
	factory.setPersistenceUnitName("jpaPersistenceUnit");
	factory.setJpaProperties(jpaProperties());
	factory.setJpaDialect(new HibernateJpaDialect());

	return factory;
}
 
Example 51
Project: holon-datastore-jpa   File: TestEnableDatastore.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
public FactoryBean<EntityManagerFactory> entityManagerFactory(DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);
	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain1.class.getPackage().getName());
	return emf;
}
 
Example 52
Project: holon-datastore-jpa   File: TestEnableDatastoreMulti.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
public FactoryBean<EntityManagerFactory> entityManagerFactory1(@Qualifier("one") DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);
	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain1.class.getPackage().getName());
	emf.setPersistenceUnitName("one");
	return emf;
}
 
Example 53
Project: holon-datastore-jpa   File: TestEnableDatastoreMulti.java   Source Code and License 5 votes vote down vote up
@Bean
@Qualifier("two")
public FactoryBean<EntityManagerFactory> entityManagerFactory2(@Qualifier("two") DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);
	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain2.class.getPackage().getName());
	emf.setPersistenceUnitName("two");
	return emf;
}
 
Example 54
Project: holon-datastore-jpa   File: ExampleJpaDatastoreSpring.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory(DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
	emf.setPackagesToScan("com.exmaple.test.entities");
	return emf;
}
 
Example 55
Project: holon-datastore-jpa   File: TestDatastoreMultiConditional.java   Source Code and License 5 votes vote down vote up
@Bean
@Qualifier("one")
public FactoryBean<EntityManagerFactory> entityManagerFactory1(DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);
	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain1.class.getPackage().getName());
	return emf;
}
 
Example 56
Project: holon-datastore-jpa   File: TestDatastoreMultiConditional.java   Source Code and License 5 votes vote down vote up
@Bean
@Qualifier("two")
public FactoryBean<EntityManagerFactory> entityManagerFactory2(DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);
	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain2.class.getPackage().getName());
	return emf;
}
 
Example 57
Project: holon-datastore-jpa   File: TestJpaDatastoreEclipselink.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource());

	EclipseLinkJpaVendorAdapter va = new EclipseLinkJpaVendorAdapter();
	va.setShowSql(true);

	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName());
	emf.setPersistenceUnitName("test");
	emf.getJpaPropertyMap().put("eclipselink.weaving", "false");

	return emf;
}
 
Example 58
Project: holon-datastore-jpa   File: TestJpaDatastoreHibernate.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource());
	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setShowSql(true);
	emf.setJpaVendorAdapter(va);
	emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName());
	emf.setPersistenceUnitName("test");
	emf.getJpaPropertyMap().put("hibernate.jdbc.batch_size", 5);
	return emf;
}
 
Example 59
Project: holon-datastore-jpa   File: TestMultiTenancy.java   Source Code and License 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory() {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource());

	HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
	va.setDatabase(Database.H2);
	emf.setJpaVendorAdapter(va);

	emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName());
	emf.setPersistenceUnitName("test");
	return emf;
}
 
Example 60
Project: holon-jdbc   File: TestBase.java   Source Code and License 5 votes vote down vote up
@Test
public void testFactoryBean() {
	TestUtils.expectedException(BeanInitializationException.class, new Callable<DataSource>() {

		@Override
		public DataSource call() throws Exception {
			FactoryBean<DataSource> fb = new DataSourceFactoryBean(
					SpringDataSourceConfigProperties.builder().withPropertySource(new Properties()).build());
			return fb.getObject();
		}
	});
}