org.springframework.beans.factory.BeanCreationException Java Examples

The following examples show how to use org.springframework.beans.factory.BeanCreationException. 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: AutowiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomAnnotationRequiredMethodResourceInjectionFailsWhenMultipleDependenciesFound() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setAutowiredAnnotationType(MyAutowired.class);
	bpp.setRequiredParameterName("optional");
	bpp.setRequiredParameterValue(false);
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	bf.registerBeanDefinition("customBean", new RootBeanDefinition(
			CustomAnnotationRequiredMethodResourceInjectionBean.class));
	TestBean tb1 = new TestBean();
	bf.registerSingleton("testBean1", tb1);
	TestBean tb2 = new TestBean();
	bf.registerSingleton("testBean2", tb2);

	try {
		bf.getBean("customBean");
		fail("expected BeanCreationException; multiple beans of dependency type available");
	}
	catch (BeanCreationException e) {
		// expected
	}
	bf.destroySingletons();
}
 
Example #2
Source File: ConsulServiceDiscoveryAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void postConstruct() {
    if (beanFactory != null) {
        Map<String, Object> parameters = new HashMap<>();

        for (Map.Entry<String, ConsulServiceCallServiceDiscoveryConfigurationCommon> entry : configuration.getConfigurations().entrySet()) {
            // clean up params
            parameters.clear();

            // The instance factory
            ConsulServiceDiscoveryFactory factory = new ConsulServiceDiscoveryFactory();

            try {
                IntrospectionSupport.getProperties(entry.getValue(), parameters, null, false);
                IntrospectionSupport.setProperties(camelContext, camelContext.getTypeConverter(), factory, parameters);

                beanFactory.registerSingleton(entry.getKey(), factory.newInstance(camelContext));
            } catch (Exception e) {
                throw new BeanCreationException(entry.getKey(), e.getMessage(), e);
            }
        }
    }
}
 
Example #3
Source File: RequiredAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testWithRequiredPropertyOmitted() {
	try {
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.addPropertyValue("name", "Rob Harrop")
			.addPropertyValue("favouriteColour", "Blue")
			.addPropertyValue("jobTitle", "Grand Poobah")
			.getBeanDefinition();
		factory.registerBeanDefinition("testBean", beanDef);
		factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
		factory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		String message = ex.getCause().getMessage();
		assertTrue(message.contains("Property"));
		assertTrue(message.contains("age"));
		assertTrue(message.contains("testBean"));
	}
}
 
Example #4
Source File: DataFlowServerConfigurationTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that embedded h2 does not start if h2 url is specified with with the
 * spring.dataflow.embedded.database.enabled is set to false.
 *
 * @throws Throwable if any error occurs and should be handled by the caller.
 */
@Test(expected = ConnectException.class)
public void testDoNotStartEmbeddedH2Server() throws Throwable {
	Throwable exceptionResult = null;
	Map<String, Object> myMap = new HashMap<>();
	myMap.put("spring.datasource.url", "jdbc:h2:tcp://localhost:19092/mem:dataflow");
	myMap.put("spring.dataflow.embedded.database.enabled", "false");
	myMap.put("spring.jpa.database", "H2");
	propertySources.addFirst(new MapPropertySource("EnvironmentTestPropsource", myMap));
	context.setEnvironment(environment);
	try {
		context.refresh();
	}
	catch (BeanCreationException exception) {
		exceptionResult = exception.getRootCause();
	}
	assertNotNull(exceptionResult);
	throw exceptionResult;
}
 
Example #5
Source File: JobsAutoConfiguration.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link ProcessChecker.Factory} suitable for UNIX systems.
 *
 * @param executor       The executor where checks are executed
 * @param jobsProperties The jobs properties
 * @return a {@link ProcessChecker.Factory}
 */
@Bean
@ConditionalOnMissingBean(ProcessChecker.Factory.class)
public ProcessChecker.Factory processCheckerFactory(
    final Executor executor,
    final JobsProperties jobsProperties
) {
    if (SystemUtils.IS_OS_UNIX) {
        return new UnixProcessChecker.Factory(
            executor,
            jobsProperties.getUsers().isRunAsUserEnabled()
        );
    } else {
        throw new BeanCreationException("No implementation available for non-UNIX systems");
    }
}
 
Example #6
Source File: BeanValidationPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSizeConstraint() {
	GenericApplicationContext ac = new GenericApplicationContext();
	ac.registerBeanDefinition("bvpp", new RootBeanDefinition(BeanValidationPostProcessor.class));
	RootBeanDefinition bd = new RootBeanDefinition(NotNullConstrainedBean.class);
	bd.getPropertyValues().add("testBean", new TestBean());
	bd.getPropertyValues().add("stringValue", "s");
	ac.registerBeanDefinition("bean", bd);
	try {
		ac.refresh();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getRootCause().getMessage().contains("stringValue"));
		assertTrue(ex.getRootCause().getMessage().contains("invalid"));
	}
	ac.close();
}
 
Example #7
Source File: ConfigurationClassPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void configurationClassesWithInvalidOverridingForProgrammaticCall() {
	beanFactory.registerBeanDefinition("config1", new RootBeanDefinition(InvalidOverridingSingletonBeanConfig.class));
	beanFactory.registerBeanDefinition("config2", new RootBeanDefinition(OverridingSingletonBeanConfig.class));
	beanFactory.registerBeanDefinition("config3", new RootBeanDefinition(SingletonBeanConfig.class));
	ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
	pp.postProcessBeanFactory(beanFactory);

	try {
		beanFactory.getBean(Bar.class);
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getMessage().contains("OverridingSingletonBeanConfig.foo"));
		assertTrue(ex.getMessage().contains(ExtendedFoo.class.getName()));
		assertTrue(ex.getMessage().contains(Foo.class.getName()));
		assertTrue(ex.getMessage().contains("InvalidOverridingSingletonBeanConfig"));
	}
}
 
Example #8
Source File: ServletContextSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void testServletContextParameterFactoryBeanWithAttributeNotFound() {
	MockServletContext sc = new MockServletContext();

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("initParamName", "myParam");
	wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs);

	try {
		wac.refresh();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
		assertTrue(ex.getCause() instanceof IllegalStateException);
		assertTrue(ex.getCause().getMessage().contains("myParam"));
	}
}
 
Example #9
Source File: RequestScopeTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void circleLeadsToException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		String name = "requestScopedObjectCircle1";
		assertNull(request.getAttribute(name));

		this.beanFactory.getBean(name);
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #10
Source File: QualifierAnnotationAutowireContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutowiredConstructorArgumentWithMultipleNonQualifiedCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #11
Source File: BeanDefinitionValueResolver.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve a reference to another bean in the factory.
 */
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
	try {
		String refName = ref.getBeanName();
		refName = String.valueOf(evaluate(refName));
		if (ref.isToParent()) {
			if (this.beanFactory.getParentBeanFactory() == null) {
				throw new BeanCreationException(
						this.beanDefinition.getResourceDescription(), this.beanName,
						"Can't resolve reference to bean '" + refName +
						"' in parent factory: no parent factory available");
			}
			return this.beanFactory.getParentBeanFactory().getBean(refName);
		}
		else {
			Object bean = this.beanFactory.getBean(refName);
			this.beanFactory.registerDependentBean(refName, this.beanName);
			return bean;
		}
	}
	catch (BeansException ex) {
		throw new BeanCreationException(
				this.beanDefinition.getResourceDescription(), this.beanName,
				"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
	}
}
 
Example #12
Source File: NettyRpcClientBeanDefinitionRegistrar.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
private void registerNettyRpcClient(AnnotatedBeanDefinition beanDefinition,BeanDefinitionRegistry registry)  {
    AnnotationMetadata metadata = beanDefinition.getMetadata();
    Map<String, Object> nettyRpcClientAttributes = metadata.getAnnotationAttributes(nettyRpcClientCanonicalName);
    Map<String, Object> lazyAttributes = metadata.getAnnotationAttributes(lazyCanonicalName);

    Class<?> beanClass;
    try {
        beanClass = ClassUtils.forName(metadata.getClassName(), classLoader);
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException("NettyRpcClientsRegistrar failure! notfound class",e);
    }

    String serviceName = resolve((String) nettyRpcClientAttributes.get("serviceName"));
    beanDefinition.setLazyInit(lazyAttributes == null || Boolean.TRUE.equals(lazyAttributes.get("value")));
    ((AbstractBeanDefinition)beanDefinition).setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    ((AbstractBeanDefinition)beanDefinition).setInstanceSupplier(newInstanceSupplier(beanClass,serviceName,(int)nettyRpcClientAttributes.get("timeout")));

    String beanName = generateBeanName(beanDefinition.getBeanClassName());
    registry.registerBeanDefinition(beanName,beanDefinition);
}
 
Example #13
Source File: QualifierAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldWithMultipleNonQualifiedCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #14
Source File: InjectAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAutowiredMethodParameterWithSingleNonQualifiedCandidate() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs = new ConstructorArgumentValues();
	cavs.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
	context.registerBeanDefinition(JUERGEN, person);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #15
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return a BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
	try {
		Object beanInstance;
		final BeanFactory parent = this;
		if (System.getSecurityManager() != null) {
			beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
					getInstantiationStrategy().instantiate(mbd, beanName, parent),
					getAccessControlContext());
		}
		else {
			beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
		}
		BeanWrapper bw = new BeanWrapperImpl(beanInstance);
		initBeanWrapper(bw);
		return bw;
	}
	catch (Throwable ex) {
		throw new BeanCreationException(
				mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
	}
}
 
Example #16
Source File: ServletContextSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void testServletContextParameterFactoryBeanWithAttributeNotFound() {
	MockServletContext sc = new MockServletContext();

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("initParamName", "myParam");
	wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs);

	try {
		wac.refresh();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
		assertTrue(ex.getCause() instanceof IllegalStateException);
		assertTrue(ex.getCause().getMessage().contains("myParam"));
	}
}
 
Example #17
Source File: QualifierAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void autowiredConstructorArgumentWithMultipleNonQualifiedCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #18
Source File: FailFastLoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailToStartContextWhenNoStubCanBeFound() {
	// When
	final Throwable throwable = catchThrowable(() -> new SpringApplicationBuilder(
			Application.class, StubRunnerConfiguration.class)
					.properties(ImmutableMap.of("stubrunner.stubsMode", "REMOTE",
							"stubrunner.repositoryRoot",
							"classpath:m2repo/repository/", "stubrunner.ids",
							new String[] {
									"org.springframework.cloud.contract.verifier.stubs:should-not-be-found" }))
					.run());

	// Then
	assertThat(throwable).isInstanceOf(BeanCreationException.class);
	assertThat(throwable.getCause().getCause())
			.isInstanceOf(BeanInstantiationException.class).hasMessageContaining(
					"No stubs or contracts were found for [org.springframework.cloud.contract.verifier.stubs:should-not-be-found:+:stubs] and the switch to fail on no stubs was set.");
}
 
Example #19
Source File: EventSourceBeanRegistrar.java    From synapse with Apache License 2.0 6 votes vote down vote up
@Override
protected void registerBeanDefinitions(final String channelName,
                                       final String beanName,
                                       final AnnotationAttributes annotationAttributes,
                                       final BeanDefinitionRegistry registry) {
    final Class<? extends MessageLog> channelSelector = annotationAttributes.getClass("selector");
    final String messageLogBeanName = Objects.toString(
            emptyToNull(annotationAttributes.getString("messageLogReceiverEndpoint")),
            beanNameForMessageLogReceiverEndpoint(channelName));

    if (!registry.containsBeanDefinition(messageLogBeanName)) {
        registerMessageLogBeanDefinition(registry, messageLogBeanName, channelName, channelSelector);
    } else {
        throw new BeanCreationException(messageLogBeanName, format("MessageLogReceiverEndpoint %s is already registered.", messageLogBeanName));
    }
    if (!registry.containsBeanDefinition(beanName)) {
        registerEventSourceBeanDefinition(registry, beanName, messageLogBeanName, channelName, channelSelector);
    } else {
        throw new BeanCreationException(beanName, format("EventSource %s is already registered.", beanName));
    }
}
 
Example #20
Source File: AbstractBeanFactory.java    From blog_demos with Apache License 2.0 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 #21
Source File: XmlBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonLenientDependencyMatchingFactoryMethod() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
	AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBeanFactoryMethod");
	bd.setLenientConstructorResolution(false);
	try {
		xbf.getBean("lenientDependencyTestBeanFactoryMethod");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getMostSpecificCause().getMessage().contains("Ambiguous"));
	}
}
 
Example #22
Source File: ClassPathBeanDefinitionScannerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutowireCandidatePatternDoesNotMatch() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(true);
	scanner.setBeanNameGenerator(new TestBeanNameGenerator());
	scanner.setAutowireCandidatePatterns(new String[] { "*NoSuchDao" });
	scanner.scan(BASE_PACKAGE);
	try {
		context.refresh();
		context.getBean("fooService");
		fail("BeanCreationException expected; fooDao should not have been an autowire-candidate");
	}
	catch (BeanCreationException expected) {
		assertTrue(expected.getMostSpecificCause() instanceof NoSuchBeanDefinitionException);
	}
}
 
Example #23
Source File: HazelcastJetAutoConfigurationServerTests.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
@Test
public void unknownSystemPropertyConfigImdgFile() {
    contextRunner
            .withSystemProperties("hazelcast.config=foo/bar/unknown.xml")
            .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)
                                                 .hasMessageContaining("foo/bar/unknown.xml"));
}
 
Example #24
Source File: SparkYarnTaskPropertiesTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Test(expected = BeanCreationException.class)
public void testSparkAssemblyJarIsRequired() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(context, "spark.app-class: Dummy");
    EnvironmentTestUtils.addEnvironment(context, "spark.app-jar: dummy.jar");
    context.register(Conf.class);
    context.refresh();
}
 
Example #25
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			result.put(beanName, getBean(beanName, type));
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				if (isCurrentlyInCreation(bce.getBeanName())) {
					if (this.logger.isDebugEnabled()) {
						this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #26
Source File: ProxyFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTargetSourceNotAtEndOfInterceptorNamesIsRejected() {
	try {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(NOTLAST_TARGETSOURCE_CONTEXT, CLASS));
		bf.getBean("targetSourceNotLast");
		fail("TargetSource or non-advised object must be last in interceptorNames");
	}
	catch (BeanCreationException ex) {
		// Root cause of the problem must be an AOP exception
		AopConfigException aex = (AopConfigException) ex.getCause();
		assertTrue(aex.getMessage().indexOf("interceptorNames") != -1);
	}
}
 
Example #27
Source File: SpringBootPropertyApplicationTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void bindInvalidProperties() {
    this.context.register(SpringBootPropertyApplication.class);
    this.context.getEnvironment().getSystemProperties();
    TestPropertyValues.of("validator.host:xxxxxx", "validator.port:9090").applyTo(this.context);
    assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh)
        .withMessageContaining("Failed to bind properties under 'validator'");
}
 
Example #28
Source File: ResilienceAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void postConstruct() {
    if (beanFactory == null) {
        return;
    }

    Map<String, Object> properties = new HashMap<>();

    for (Map.Entry<String, Resilience4jConfigurationDefinitionCommon> entry : config.getConfigurations().entrySet()) {

        // clear the properties map for reuse
        properties.clear();

        // extract properties
        IntrospectionSupport.getProperties(entry.getValue(), properties, null, false);

        try {
            Resilience4jConfigurationDefinition definition = new Resilience4jConfigurationDefinition();
            IntrospectionSupport.setProperties(camelContext, camelContext.getTypeConverter(), definition, properties);

            // Registry the definition
            beanFactory.registerSingleton(entry.getKey(), definition);

        } catch (Exception e) {
            throw new BeanCreationException(entry.getKey(), e);
        }
    }
}
 
Example #29
Source File: PluginsConfig.java    From nakadi with MIT License 5 votes vote down vote up
@Bean
@SuppressWarnings("unchecked")
public ApplicationService applicationService(@Value("${nakadi.plugins.auth.factory}") final String factoryName,
                                             final SystemProperties systemProperties,
                                             final DefaultResourceLoader loader) {
    try {
        LOGGER.info("Initialize application service factory: " + factoryName);
        final Class<ApplicationServiceFactory> factoryClass =
                (Class<ApplicationServiceFactory>) loader.getClassLoader().loadClass(factoryName);
        final ApplicationServiceFactory factory = factoryClass.newInstance();
        return factory.init(systemProperties);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new BeanCreationException("Can't create ApplicationService " + factoryName, e);
    }
}
 
Example #30
Source File: FactoryBeanRegistrySupport.java    From lams with GNU General Public License v2.0 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;
}