org.springframework.beans.BeanInstantiationException Java Examples

The following examples show how to use org.springframework.beans.BeanInstantiationException. 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: ClassPathBeanDefinitionScannerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBeanNotAutowiredWithAnnotationConfigDisabled() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator(new TestBeanNameGenerator());
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(7, beanCount);
	context.refresh();

	try {
		context.getBean("fooService");
	}
	catch (BeanCreationException expected) {
		assertTrue(expected.contains(BeanInstantiationException.class));
		// @Lookup method not substituted
	}
}
 
Example #2
Source File: SolrClientUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private static LBHttpSolrClient cloneLBHttpSolrClient(SolrClient solrClient, String core) {
	if (solrClient == null) {
		return null;
	}

	LBHttpSolrClient clone = null;
	try {
		if (VersionUtil.isSolr3XAvailable()) {
			clone = cloneSolr3LBHttpServer(solrClient, core);
		} else if (VersionUtil.isSolr4XAvailable()) {
			clone = cloneSolr4LBHttpServer(solrClient, core);
		}
	} catch (Exception e) {
		throw new BeanInstantiationException(solrClient.getClass(),
				"Cannot create instace of " + solrClient.getClass() + ". ", e);
	}
	Object o = readField(solrClient, "interval");
	if (o != null) {
		clone.setAliveCheckInterval(Integer.valueOf(o.toString()).intValue());
	}
	return clone;
}
 
Example #3
Source File: CglibSubclassingInstantiationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiateClass(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #4
Source File: AbstractTestContextBootstrapper.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private List<TestExecutionListener> instantiateListeners(List<Class<? extends TestExecutionListener>> classesList) {
	List<TestExecutionListener> listeners = new ArrayList<TestExecutionListener>(classesList.size());
	for (Class<? extends TestExecutionListener> listenerClass : classesList) {
		NoClassDefFoundError ncdfe = null;
		try {
			listeners.add(BeanUtils.instantiateClass(listenerClass));
		}
		catch (NoClassDefFoundError err) {
			ncdfe = err;
		}
		catch (BeanInstantiationException ex) {
			if (ex.getCause() instanceof NoClassDefFoundError) {
				ncdfe = (NoClassDefFoundError) ex.getCause();
			}
		}
		if (ncdfe != null) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format("Could not instantiate TestExecutionListener [%s]. "
						+ "Specify custom listener classes or make the default listener classes "
						+ "(and their required dependencies) available. Offending class: [%s]",
					listenerClass.getName(), ncdfe.getMessage()));
			}
		}
	}
	return listeners;
}
 
Example #5
Source File: BeanExceptionMapper.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public ErrorResponse toErrorResponse(BeanCreationException exception) {
	Throwable cause = exception.getCause();
	while (cause instanceof BeanCreationException || cause instanceof BeanInstantiationException) {
		cause = cause.getCause();
	}
	if (cause != null) {
		Optional<ExceptionMapper> mapper = context.getExceptionMapperRegistry().findMapperFor(cause.getClass());
		if (mapper.isPresent()) {
			return mapper.get().toErrorResponse(cause);
		}
	}

	LOGGER.error("failed to setup spring beans", exception);

	// no mapper found, return default error
	int status = HttpStatus.INTERNAL_SERVER_ERROR_500;
	ErrorData errorData = ErrorData.builder().setStatus(Integer.toString(status))
			.setTitle(exception.getMessage()).build();
	return ErrorResponse.builder().setSingleErrorData(errorData).setStatus(status).build();
}
 
Example #6
Source File: GrpcClientBeanPostProcessor.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * Creates a stub of the given type.
 *
 * @param <T> The type of the instance to be injected.
 * @param stubType The type of the stub to create.
 * @param channel The channel used to create the stub.
 * @return The newly created stub.
 *
 * @throws BeanInstantiationException If the stub couldn't be created.
 */
protected <T extends AbstractStub<T>> T createStub(final Class<T> stubType, final Channel channel) {
    try {
        // First try the public static factory method
        final String methodName = deriveStubFactoryMethodName(stubType);
        final Class<?> enclosingClass = stubType.getEnclosingClass();
        final Method factoryMethod = enclosingClass.getMethod(methodName, Channel.class);
        return stubType.cast(factoryMethod.invoke(null, channel));
    } catch (final Exception e) {
        try {
            // Use the private constructor as backup
            final Constructor<T> constructor = stubType.getDeclaredConstructor(Channel.class);
            constructor.setAccessible(true);
            return constructor.newInstance(channel);
        } catch (final Exception e1) {
            e.addSuppressed(e1);
        }
        throw new BeanInstantiationException(stubType, "Failed to create gRPC client", e);
    }
}
 
Example #7
Source File: EhCacheTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) {
        throw new BeanInstantiationException(this.getClass(),
                "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties.");
    }

    if (logger.isDebugEnabled()) {
        CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration();
        logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName());

        config = this.ticketGrantingTicketsCache.getCacheConfiguration();
        logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager()
                .getName());
    }
}
 
Example #8
Source File: EhCacheTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (this.serviceTicketsCache == null || this.ticketGrantingTicketsCache == null) {
        throw new BeanInstantiationException(this.getClass(),
                "Both serviceTicketsCache and ticketGrantingTicketsCache are required properties.");
    }

    if (logger.isDebugEnabled()) {
        CacheConfiguration config = this.serviceTicketsCache.getCacheConfiguration();
        logger.debug("serviceTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("serviceTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("serviceTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("serviceTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("serviceTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("serviceTicketsCache.cacheManager={}", this.serviceTicketsCache.getCacheManager().getName());

        config = this.ticketGrantingTicketsCache.getCacheConfiguration();
        logger.debug("ticketGrantingTicketsCache.maxElementsInMemory={}", config.getMaxEntriesLocalHeap());
        logger.debug("ticketGrantingTicketsCache.maxElementsOnDisk={}", config.getMaxElementsOnDisk());
        logger.debug("ticketGrantingTicketsCache.isOverflowToDisk={}", config.isOverflowToDisk());
        logger.debug("ticketGrantingTicketsCache.timeToLive={}", config.getTimeToLiveSeconds());
        logger.debug("ticketGrantingTicketsCache.timeToIdle={}", config.getTimeToIdleSeconds());
        logger.debug("ticketGrantingTicketsCache.cacheManager={}", this.ticketGrantingTicketsCache.getCacheManager()
                .getName());
    }
}
 
Example #9
Source File: CglibSubclassingInstantiationStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #10
Source File: GrpcClientBeanPostProcessor.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * Creates a stub of the given type.
 *
 * @param <T> The type of the instance to be injected.
 * @param stubType The type of the stub to create.
 * @param channel The channel used to create the stub.
 * @return The newly created stub.
 *
 * @throws BeanInstantiationException If the stub couldn't be created.
 */
protected <T extends AbstractStub<T>> T createStub(final Class<T> stubType, final Channel channel) {
    try {
        // First try the public static factory method
        final String methodName = deriveStubFactoryMethodName(stubType);
        final Class<?> enclosingClass = stubType.getEnclosingClass();
        final Method factoryMethod = enclosingClass.getMethod(methodName, Channel.class);
        return stubType.cast(factoryMethod.invoke(null, channel));
    } catch (final Exception e) {
        try {
            // Use the private constructor as backup
            final Constructor<T> constructor = stubType.getDeclaredConstructor(Channel.class);
            constructor.setAccessible(true);
            return constructor.newInstance(channel);
        } catch (final Exception e1) {
            e.addSuppressed(e1);
        }
        throw new BeanInstantiationException(stubType, "Failed to create gRPC client", e);
    }
}
 
Example #11
Source File: CglibSubclassingInstantiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiateClass(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #12
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 #13
Source File: AbstractTestContextBootstrapper.java    From java-technology-stack with MIT License 6 votes vote down vote up
private List<TestExecutionListener> instantiateListeners(Collection<Class<? extends TestExecutionListener>> classes) {
	List<TestExecutionListener> listeners = new ArrayList<>(classes.size());
	for (Class<? extends TestExecutionListener> listenerClass : classes) {
		try {
			listeners.add(BeanUtils.instantiateClass(listenerClass));
		}
		catch (BeanInstantiationException ex) {
			if (ex.getCause() instanceof NoClassDefFoundError) {
				// TestExecutionListener not applicable due to a missing dependency
				if (logger.isDebugEnabled()) {
					logger.debug(String.format(
							"Skipping candidate TestExecutionListener [%s] due to a missing dependency. " +
							"Specify custom listener classes or make the default listener classes " +
							"and their required dependencies available. Offending class: [%s]",
							listenerClass.getName(), ex.getCause().getMessage()));
				}
			}
			else {
				throw ex;
			}
		}
	}
	return listeners;
}
 
Example #14
Source File: FailFastLoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotTryAndWorkOfflineWhenRemoteModeIsOn() {
	// When
	final Throwable throwable = catchThrowable(() -> new SpringApplicationBuilder(
			Application.class, StubRunnerConfiguration.class)
					.properties(ImmutableMap.of("stubrunner.stubsMode", "CLASSPATH",
							"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 were found on classpath ");
}
 
Example #15
Source File: ClassPathBeanDefinitionScannerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testBeanNotAutowiredWithAnnotationConfigDisabled() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator(new TestBeanNameGenerator());
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(7, beanCount);
	context.refresh();

	try {
		context.getBean("fooService");
	}
	catch (BeanCreationException expected) {
		assertTrue(expected.contains(BeanInstantiationException.class));
		// @Lookup method not substituted
	}
}
 
Example #16
Source File: CglibSubclassingInstantiationStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiateClass(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #17
Source File: AbstractTestContextBootstrapper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private List<TestExecutionListener> instantiateListeners(Collection<Class<? extends TestExecutionListener>> classes) {
	List<TestExecutionListener> listeners = new ArrayList<>(classes.size());
	for (Class<? extends TestExecutionListener> listenerClass : classes) {
		try {
			listeners.add(BeanUtils.instantiateClass(listenerClass));
		}
		catch (BeanInstantiationException ex) {
			if (ex.getCause() instanceof NoClassDefFoundError) {
				// TestExecutionListener not applicable due to a missing dependency
				if (logger.isDebugEnabled()) {
					logger.debug(String.format(
							"Skipping candidate TestExecutionListener [%s] due to a missing dependency. " +
							"Specify custom listener classes or make the default listener classes " +
							"and their required dependencies available. Offending class: [%s]",
							listenerClass.getName(), ex.getCause().getMessage()));
				}
			}
			else {
				throw ex;
			}
		}
	}
	return listeners;
}
 
Example #18
Source File: MemcachedAutoConfigurationIT.java    From memcached-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void whenAwsProviderAndMultipleServerListThenMemcachedNotLoaded() {
    assertThatThrownBy(() ->
            loadContext(CacheConfiguration.class, String.format("memcached.cache.servers=%s:%d,%s:%d", memcachedHost1, memcachedPort1, memcachedHost2, memcachedPort2),
                    "memcached.cache.provider=aws")
    )
            .isInstanceOf(BeanCreationException.class)
            .hasCauseInstanceOf(BeanInstantiationException.class)
            .hasStackTraceContaining("Retrieve ElasticCache config from");
}
 
Example #19
Source File: SimpleInstantiationStrategy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (bd.getMethodOverrides().isEmpty()) {
		Constructor<?> constructorToUse;
		synchronized (bd.constructorArgumentLock) {
			constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				final Class<?> clazz = bd.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
							@Override
							public Constructor<?> run() throws Exception {
								return clazz.getDeclaredConstructor((Class[]) null);
							}
						});
					}
					else {
						constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
					}
					bd.resolvedConstructorOrFactoryMethod = constructorToUse;
				}
				catch (Exception ex) {
					throw new BeanInstantiationException(clazz, "No default constructor found", ex);
				}
			}
		}
		return BeanUtils.instantiateClass(constructorToUse);
	}
	else {
		// Must generate CGLIB subclass.
		return instantiateWithMethodInjection(bd, beanName, owner);
	}
}
 
Example #20
Source File: DalAnnotationValidatorTest.java    From dal with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRawBean() throws Exception {
    DalAnnotationValidator test = new DalAnnotationValidator();
    try{
        TransactionAnnoClass bean = new TransactionAnnoClass();
        test.postProcessAfterInitialization(bean, "beanName");
        fail();
    }catch(BeanInstantiationException e) {
        assertTrue(e.getMessage().contains(DalAnnotationValidator.VALIDATION_MSG));
    }
}
 
Example #21
Source File: Base.java    From iaf with Apache License 2.0 5 votes vote down vote up
protected FlowDiagramManager getFlowDiagramManager() {
	try {
		return getIbisContext().getBean("flowDiagramManager", FlowDiagramManager.class);
	} catch (BeanCreationException | BeanInstantiationException | NoSuchBeanDefinitionException e) {
		throw new ApiException("failed to initalize FlowDiagramManager", e);
	}
}
 
Example #22
Source File: FlowDiagramManager.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	try {
		IFlowGenerator generator = applicationContext.getBean("flowGenerator", IFlowGenerator.class);
		setFlowGenerator(generator);
	} catch (BeanCreationException | BeanInstantiationException | NoSuchBeanDefinitionException e) {
		//Failed to initialise.
		log.warn("failed to initalize IFlowGenerator", e);
	}
}
 
Example #23
Source File: BeanCreatingHandlerProviderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected=BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

	BeanCreatingHandlerProvider<EchoHandler> provider =
			new BeanCreatingHandlerProvider<EchoHandler>(EchoHandler.class);

	provider.getHandler();
}
 
Example #24
Source File: ConfigurableFieldFactory.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Field createField(Item item, Object propertyId, Component uiContext) {
	Class<Field> clazz = fieldMap.get(propertyId);
	if (clazz != null) {
		try {
			return BeanUtils.instantiate(clazz);
		}
		catch(BeanInstantiationException bie) {
			log.error(bie);
		}
	}
	
	return null;
}
 
Example #25
Source File: CustomNamespaceHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxyingDecoratorNoInstance() throws Exception {
	String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.class);
	assertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance"));
	assertEquals(ApplicationListener.class, this.beanFactory.getType("debuggingTestBeanNoInstance"));
	try {
		this.beanFactory.getBean("debuggingTestBeanNoInstance");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.getRootCause() instanceof BeanInstantiationException);
	}
}
 
Example #26
Source File: CglibSubclassingInstantiationStrategy.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
Object instantiate(Constructor<?> ctor, Object[] args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);

	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception e) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format(
				"Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e);
		}
	}

	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] { NoOp.INSTANCE,//
		new LookupOverrideMethodInterceptor(beanDefinition, owner),//
		new ReplaceOverrideMethodInterceptor(beanDefinition, owner) });

	return instance;
}
 
Example #27
Source File: SimpleInstantiationStrategy.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (beanDefinition.getMethodOverrides().isEmpty()) {
		Constructor<?> constructorToUse;
		synchronized (beanDefinition.constructorArgumentLock) {
			constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				final Class<?> clazz = beanDefinition.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
							@Override
							public Constructor<?> run() throws Exception {
								return clazz.getDeclaredConstructor((Class[]) null);
							}
						});
					}
					else {
						constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
					}
					beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
				}
				catch (Exception ex) {
					throw new BeanInstantiationException(clazz, "No default constructor found", ex);
				}
			}
		}
		return BeanUtils.instantiateClass(constructorToUse);
	}
	else {
		// Must generate CGLIB subclass.
		return instantiateWithMethodInjection(beanDefinition, beanName, owner);
	}
}
 
Example #28
Source File: SolrClientUtils.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static SolrClient cloneEmbeddedSolrServer(SolrClient solrClient, String core) {

	CoreContainer coreContainer = ((EmbeddedSolrServer) solrClient).getCoreContainer();
	try {
		Constructor constructor = ClassUtils.getConstructorIfAvailable(solrClient.getClass(), CoreContainer.class,
				String.class);
		return (SolrClient) BeanUtils.instantiateClass(constructor, coreContainer, core);
	} catch (Exception e) {
		throw new BeanInstantiationException(solrClient.getClass(),
				"Cannot create instace of " + solrClient.getClass() + ".", e);
	}
}
 
Example #29
Source File: SimpleInstantiationStrategy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (bd.getMethodOverrides().isEmpty()) {
		Constructor<?> constructorToUse;
		synchronized (bd.constructorArgumentLock) {
			constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				final Class<?> clazz = bd.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
							@Override
							public Constructor<?> run() throws Exception {
								return clazz.getDeclaredConstructor((Class[]) null);
							}
						});
					}
					else {
						constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
					}
					bd.resolvedConstructorOrFactoryMethod = constructorToUse;
				}
				catch (Throwable ex) {
					throw new BeanInstantiationException(clazz, "No default constructor found", ex);
				}
			}
		}
		return BeanUtils.instantiateClass(constructorToUse);
	}
	else {
		// Must generate CGLIB subclass.
		return instantiateWithMethodInjection(bd, beanName, owner);
	}
}
 
Example #30
Source File: ColaBeanInstantiationStrategy.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Return an instance of the bean with the given name in this factory.
 * @param bd the bean definition
 * @param beanName the name of the bean when it's created in this context.
 * The name can be {@code null} if we're autowiring a bean which doesn't
 * belong to the factory.
 * @param owner the owning BeanFactory
 * @return a bean instance for this bean definition
 * @throws BeansException if the instantiation attempt failed
 */
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)
    throws BeansException{
    try{
        if(filterInstantiate(bd.getTargetType())){
            return newInstance(bd.getTargetType());
        }
        return super.instantiate(bd, beanName, owner);
    }catch (BeanInstantiationException e){
        return newInstance(bd.getTargetType());
    }
}