类org.springframework.beans.BeanInstantiationException源码实例Demo

下面列出了怎么用org.springframework.beans.BeanInstantiationException的API类实例代码及写法,或者点击链接到github查看源代码。

@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
	}
}
 
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;
}
 
/**
 * 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;
}
 
@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
	}
}
 
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;
}
 
/**
 * 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;
}
 
@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());
    }
}
 
@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());
    }
}
 
/**
 * 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);
    }
}
 
源代码10 项目: crnk-framework   文件: BeanExceptionMapper.java
@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();
}
 
/**
 * 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;
}
 
源代码12 项目: dubbox   文件: SolrClientUtils.java
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;
}
 
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;
}
 
/**
 * 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;
}
 
/**
 * 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);
    }
}
 
@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
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 ");
}
 
@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);
	}
}
 
@Test(expected = BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

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

	provider.getHandler();
}
 
@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);
	}
}
 
@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);
	}
}
 
@Test(expected = BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

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

	provider.getHandler();
}
 
@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);
	}
}
 
源代码24 项目: COLA   文件: ColaBeanInstantiationStrategy.java
/**
 * 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());
    }
}
 
源代码25 项目: lams   文件: SimpleInstantiationStrategy.java
@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);
	}
}
 
源代码26 项目: dubbox   文件: SolrClientUtils.java
@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);
	}
}
 
源代码27 项目: blog_demos   文件: SimpleInstantiationStrategy.java
@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);
	}
}
 
/**
 * 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;
}
 
@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);
	}
}
 
@Test(expected=BeanInstantiationException.class)
public void getHandlerNoBeanFactory() {

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

	provider.getHandler();
}
 
 同包方法