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

The following examples show how to use org.springframework.beans.factory.BeanCreationException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: synapse   Source File: EventSourceBeanRegistrar.java    License: 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 2
@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 3
Source Project: java-technology-stack   Source File: ServletContextSupportTests.java    License: 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 4
@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 5
@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 6
@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 Project: spring-analysis-note   Source File: ServletContextSupportTests.java    License: 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 8
@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 9
@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 10
@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 11
Source Project: blog_demos   Source File: AbstractBeanFactory.java    License: 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 12
/**
 * 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 13
Source Project: genie   Source File: JobsAutoConfiguration.java    License: 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 14
@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 15
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 16
@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 17
@Test
public void responseBodyArgMismatch() throws Exception {
	initServlet(wac -> {
		Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
		marshaller.setClassesToBeBound(A.class, B.class);
		try {
			marshaller.afterPropertiesSet();
		}
		catch (Exception ex) {
			throw new BeanCreationException(ex.getMessage(), ex);
		}
		MarshallingHttpMessageConverter messageConverter = new MarshallingHttpMessageConverter(marshaller);

		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		adapterDef.getPropertyValues().add("messageConverters", messageConverter);
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, RequestBodyArgMismatchController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "<b/>";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "application/xml; charset=utf-8");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals(400, response.getStatus());
}
 
Example 18
/**
 * 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 19
Source Project: spring-analysis-note   Source File: RequestScopeTests.java    License: 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 20
Source Project: blog_demos   Source File: BeanDefinitionValueResolver.java    License: 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 21
@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 22
Source Project: spring4-understanding   Source File: XmlBeanFactoryTests.java    License: 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 23
@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 24
@Test
public void unknownConfigPropertyImdgFile() {
    contextRunner
            .withPropertyValues("hazelcast.jet.imdg.config=foo/bar/unknown.xml")
            .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)
                                                 .hasMessageContaining("foo/bar/unknown.xml"));
}
 
Example 25
@Override
public PropertyValues postProcessPropertyValues(
		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

	InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
	try {
		metadata.inject(bean, beanName, pvs);
	}
	catch (Throwable ex) {
		throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
	}
	return pvs;
}
 
Example 26
Source Project: dubbox   Source File: ConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
 
Example 27
Source Project: spring-analysis-note   Source File: CallbacksSecurityTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCustomFactoryObject() throws Exception {
	try {
		beanFactory.getBean("spring-factory");
		fail("expected security exception");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getCause() instanceof SecurityException);
	}

}
 
Example 28
@Test(expected = BeanCreationException.class) public void builderRequired() {
  context = new XmlBeans(""
    + "<bean id=\"correlationDecorator\" class=\"brave.spring.beans.CorrelationScopeDecoratorFactoryBean\">\n"
    + "</bean>"
  );

  context.getBean("correlationDecorator", CorrelationScopeDecorator.class);
}
 
Example 29
@Test
public void testEmptyInterceptorNames() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(INVALID_CONTEXT, CLASS));
	try {
		bf.getBean("emptyInterceptorNames");
		fail("Interceptor names cannot be empty");
	}
	catch (BeanCreationException ex) {
		// Ok
	}
}
 
Example 30
Source Project: spring4-understanding   Source File: FactoryMethodTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFactoryMethodNoMatchingStaticMethod() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
	try {
		xbf.getBean("noMatchPrototype");
		fail("No static method matched");
	}
	catch (BeanCreationException ex) {
		// Ok
	}
}