Java Code Examples for org.springframework.beans.BeanInstantiationException

The following examples show how to use org.springframework.beans.BeanInstantiationException. 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 check out the related API usage on the sidebar.
Example 1
@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
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 3
/**
 * 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 4
@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 5
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 6
/**
 * 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 7
@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
@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
/**
 * 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 10
Source Project: crnk-framework   Source File: BeanExceptionMapper.java    License: 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 11
/**
 * 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 12
Source Project: dubbox   Source File: SolrClientUtils.java    License: 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 13
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 14
/**
 * 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 15
/**
 * 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 16
@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 17
@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 18
Source Project: spring-analysis-note   Source File: CustomNamespaceHandlerTests.java    License: MIT License 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 19
@Test(expected = BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

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

	provider.getHandler();
}
 
Example 20
Source Project: spring-analysis-note   Source File: SimpleInstantiationStrategy.java    License: MIT License 5 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (!bd.hasMethodOverrides()) {
		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(
								(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
					}
					else {
						constructorToUse = clazz.getDeclaredConstructor();
					}
					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 21
@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 22
@Test(expected = BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

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

	provider.getHandler();
}
 
Example 23
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (!bd.hasMethodOverrides()) {
		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(
								(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
					}
					else {
						constructorToUse = clazz.getDeclaredConstructor();
					}
					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 24
/**
 * 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());
    }
}
 
Example 25
@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 26
Source Project: dubbox   Source File: SolrClientUtils.java    License: 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 27
Source Project: blog_demos   Source File: SimpleInstantiationStrategy.java    License: 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
/**
 * 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 29
@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 30
@Test(expected=BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

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

	provider.getHandler();
}