下面列出了怎么用org.springframework.beans.factory.BeanCreationException的API类实例代码及写法,或者点击链接到github查看源代码。
@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));
}
}
@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.");
}
@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"));
}
}
@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());
}
}
@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());
}
}
@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();
}
@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"));
}
}
@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"));
}
}
@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());
}
}
@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());
}
}
/**
* 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;
}
}
/**
* 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);
}
}
/**
* 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");
}
}
@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);
}
}
}
}
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);
}
@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"));
}
}
/**
* 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;
}
@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));
}
}
/**
* 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);
}
}
@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();
}
@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"));
}
}
@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);
}
}
@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"));
}
@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;
}
@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"));
}
}
@Test
public void testCustomFactoryObject() throws Exception {
try {
beanFactory.getBean("spring-factory");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
}
@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);
}
@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
}
}
@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
}
}
@Test
public void testCircularReferencesWithWrapping() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.loadBeanDefinitions(REFTYPES_CONTEXT);
xbf.addBeanPostProcessor(new WrappingPostProcessor());
try {
xbf.getBean("jenny");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
}
}