Java 类org.springframework.beans.factory.BeanNotOfRequiredTypeException 实例源码

项目:holon-core    文件:DatastoreInitializer.java   
/**
 * Register {@link DatastoreResolver} annotated beans as <code>datastore</code> {@link ExpressionResolver}s.
 * @param datastore Datastore to configure
 * @param datastoreBeanName Datastore bean name to configure
 * @param beanFactory Bean factory
 */
private static void configureDatastoreResolvers(Datastore datastore, String datastoreBeanName,
        ListableBeanFactory beanFactory) {
    final String[] beanNames = beanFactory.getBeanNamesForAnnotation(DatastoreResolver.class);
    if (beanNames != null && beanNames.length > 0) {
        for (String beanName : beanNames) {
            if (!ExpressionResolver.class.isAssignableFrom(beanFactory.getType(beanName))) {
                throw new BeanNotOfRequiredTypeException(beanName, ExpressionResolver.class,
                        beanFactory.getType(beanName));
            }
            DatastoreResolver dr = beanFactory.findAnnotationOnBean(beanName, DatastoreResolver.class);
            String datastoreRef = AnnotationUtils.getStringValue(dr.datastoreBeanName());
            if (datastoreRef == null || datastoreRef.equals(datastoreBeanName)) {
                // register resolver
                ExpressionResolver<?, ?> resolver = (ExpressionResolver<?, ?>) beanFactory.getBean(beanName);
                datastore.addExpressionResolver(resolver);
                LOGGER.debug(() -> "Registered expression resolver [" + resolver.getClass().getName()
                        + "] into Datastore with bean name [" + datastoreBeanName + "]");
            }
        }
    }
}
项目:holon-jdbc    文件:DataContextDataSourceInitializer.java   
@PostConstruct
public void init() {
    if (!configuration.isInitialize()) {
        LOGGER.debug(() -> "Initialization disabled (not running DDL scripts) for data context id: ["
                + getDataContextId().orElse("DEFAULT") + "]");
        return;
    }
    DataSource dataSource = null;
    try {
        dataSource = applicationContext.getBean(dataSourceBeanName, DataSource.class);
    } catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException | BeanNotOfRequiredTypeException e) {
        // ignore
    }
    if (dataSource == null) {
        LOGGER.debug(() -> "No DataSource found using bean name " + dataSourceBeanName + ": skip initialization");
        return;
    }
    runSchemaScripts(dataSource);
}
项目:spring-modular    文件:ExportTargetSource.java   
public Object getTarget() throws BeansException {
    Object localTarget = target.get();

    if (localTarget == null) {
        // verify if declared service interface is compatible with the real bean type
        Class<?> beanClass = beanFactory.getType(beanName);
        if (!serviceInterface.isAssignableFrom(beanClass)) {
            throw new BeanNotOfRequiredTypeException(beanName, serviceInterface, beanClass);
        }

        if (target.compareAndSet(null, localTarget = beanFactory.getBean(beanName))) {
            return localTarget;

        } else {
            log.debug("Redundant initialization of ExportTargetSource for bean '{}' caused by" +
                     "concurrency has been detected.", beanName);
            return target.get();
        }
    }
    return localTarget;
}
项目:spring-modular    文件:LookupTargetSource.java   
public Object getTarget() throws BeansException {
    Object localTarget = target.get();

    if (localTarget == null) {
        if (!rootContext.containsBean(exportProxyName)) {
            throw new NoSuchBeanDefinitionException(exportProxyName, String.format(
                    "can't find export declaration for lookup(%s, %s)", serviceName, serviceInterface));
        }
        ExportTargetSource exportProxy = rootContext.getBean(exportProxyName, ExportTargetSource.class);

        // verify if service interfaces on both sides are compatible
        if (!serviceInterface.isAssignableFrom(exportProxy.getTargetClass())) {
            throw new BeanNotOfRequiredTypeException(serviceName, serviceInterface, exportProxy.getTargetClass());
        }

        if (target.compareAndSet(null, localTarget = exportProxy.getTarget())) {
            return localTarget;

        } else {
            // log potentially redundant instance initialization
            log.warn("Bean {} was created earlier", serviceName);
            return target.get();
        }
    }
    return localTarget;
}
项目:lams    文件:StaticListableBeanFactory.java   
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    Object bean = getBean(name);
    if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return (T) bean;
}
项目:holon-core    文件:DatastoreInitializer.java   
/**
 * Register {@link com.holonplatform.spring.DatastoreCommodityFactory} annotated beans as <code>datastore</code>
 * {@link DatastoreCommodityFactory}s.
 * @param datastore Datastore to configure
 * @param datastoreBeanName Datastore bean name to configure
 * @param beanFactory Bean factory
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void configureDatastoreCommodityFactories(Datastore datastore, String datastoreBeanName,
        ListableBeanFactory beanFactory) {
    if (datastore instanceof DatastoreCommodityRegistrar) {
        final Class<? extends DatastoreCommodityFactory> baseType = ((DatastoreCommodityRegistrar<?>) datastore)
                .getCommodityFactoryType();
        if (baseType != null) {
            final String[] beanNames = beanFactory
                    .getBeanNamesForAnnotation(com.holonplatform.spring.DatastoreCommodityFactory.class);
            if (beanNames != null && beanNames.length > 0) {
                for (String beanName : beanNames) {
                    com.holonplatform.spring.DatastoreCommodityFactory dr = beanFactory.findAnnotationOnBean(
                            beanName, com.holonplatform.spring.DatastoreCommodityFactory.class);
                    String datastoreRef = AnnotationUtils.getStringValue(dr.datastoreBeanName());
                    if (datastoreRef == null || datastoreRef.equals(datastoreBeanName)) {
                        if (!baseType.isAssignableFrom(beanFactory.getType(beanName))) {
                            throw new BeanNotOfRequiredTypeException(beanName, baseType,
                                    beanFactory.getType(beanName));
                        }
                        // register resolver
                        DatastoreCommodityFactory datastoreCommodityFactory = (DatastoreCommodityFactory) beanFactory
                                .getBean(beanName);
                        ((DatastoreCommodityRegistrar) datastore).registerCommodity(datastoreCommodityFactory);
                        LOGGER.debug(() -> "Registered factory [" + datastoreCommodityFactory.getClass().getName()
                                + "] into Datastore with bean name [" + datastoreBeanName + "]");
                    }
                }
            }
        } else {
            LOGGER.debug(
                    () -> "Datastore [" + datastore + "] does not declares a DatastoreCommodityFactory base type: "
                            + "skipping DatastoreCommodityFactory beans configuration");
        }
    } else {
        LOGGER.debug(() -> "Datastore [" + datastore
                + "] is not a DatastoreCommodityRegistrar: skipping DatastoreCommodityFactory beans configuration");
    }
}
项目:spring4-understanding    文件:BeanFactoryDataSourceLookupTests.java   
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
    final BeanFactory beanFactory = mock(BeanFactory.class);

    given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
            new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
                    DataSource.class, String.class));

    try {
            BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
            lookup.getDataSource(DATASOURCE_BEAN_NAME);
            fail("should have thrown DataSourceLookupFailureException");
    } catch (DataSourceLookupFailureException ex) { /* expected */ }
}
项目:spring4-understanding    文件:StaticListableBeanFactory.java   
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    Object bean = getBean(name);
    if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return (T) bean;
}
项目:spring4-understanding    文件:AbstractBeanFactoryTests.java   
@Test
public void getInstanceByNonmatchingClass() {
    try {
        getBeanFactory().getBean("rod", BeanFactory.class);
        fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
    }
    catch (BeanNotOfRequiredTypeException ex) {
        // So far, so good
        assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
        assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
        assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
        assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
    }
}
项目:spring4-understanding    文件:AbstractBeanFactoryTests.java   
@Test
public void getSharedInstanceByNonmatchingClass() {
    try {
        getBeanFactory().getBean("rod", BeanFactory.class);
        fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
    }
    catch (BeanNotOfRequiredTypeException ex) {
        // So far, so good
        assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
        assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
        assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:BeanNotOfRequiredTypeFailureAnalyzer.java   
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
        BeanNotOfRequiredTypeException cause) {
    if (!Proxy.isProxyClass(cause.getActualType())) {
        return null;
    }
    return new FailureAnalysis(getDescription(cause), ACTION, cause);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:BeanNotOfRequiredTypeFailureAnalyzer.java   
private String getDescription(BeanNotOfRequiredTypeException ex) {
    StringWriter description = new StringWriter();
    PrintWriter printer = new PrintWriter(description);
    printer.printf(
            "The bean '%s' could not be injected as a '%s' because it is a "
                    + "JDK dynamic proxy that implements:%n",
            ex.getBeanName(), ex.getRequiredType().getName());
    for (Class<?> iface : ex.getRequiredType().getInterfaces()) {
        printer.println("\t" + iface.getName());
    }
    return description.toString();
}
项目:rxjava-scheduler-spring-boot-starter    文件:TestSubscribeOnSingle.java   
@Test(expected = BeanNotOfRequiredTypeException.class)
public void shouldFailToSubscribeOnBeanIncorrectType() {

    // when
    Single result = service.invalidSchedulerType();

    // then
    assertNotNull(result);
}
项目:rxjava-scheduler-spring-boot-starter    文件:TestSubscribeOnObservable.java   
@Test(expected = BeanNotOfRequiredTypeException.class)
public void shouldFailToSubscribeOnBeanIncorrectType() {

    // when
    Observable result = service.invalidSchedulerType();

    // then
    assertNotNull(result);
}
项目:spring    文件:StaticListableBeanFactory.java   
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    Object bean = getBean(name);
    if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return (T) bean;
}
项目:class-guard    文件:BeanFactoryDataSourceLookupTests.java   
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
    final BeanFactory beanFactory = mock(BeanFactory.class);

    given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
            new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
                    DataSource.class, String.class));

    try {
            BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
            lookup.getDataSource(DATASOURCE_BEAN_NAME);
            fail("should have thrown DataSourceLookupFailureException");
    } catch (DataSourceLookupFailureException ex) { /* expected */ }
}
项目:class-guard    文件:StaticListableBeanFactory.java   
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
    Object bean = getBean(name);
    if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return (T) bean;
}
项目:spring-rich-client    文件:BeanFactoryViewDescriptorRegistryTests.java   
/**
 * Test method for {@link BeanFactoryViewDescriptorRegistry#getViewDescriptor(java.lang.String)}.
 */
public final void testGetViewDescriptor() {

    BeanFactoryViewDescriptorRegistry registry = new BeanFactoryViewDescriptorRegistry();
    StaticApplicationContext appCtx = new StaticApplicationContext();
    registry.setApplicationContext(appCtx);

    MutablePropertyValues mpv = new MutablePropertyValues();
    mpv.addPropertyValue("viewClass", NullView.class);
    appCtx.registerSingleton("view1", DefaultViewDescriptor.class, mpv);
    appCtx.registerSingleton("view2", DefaultViewDescriptor.class, mpv);
    appCtx.registerSingleton("bogusView", String.class);

    Assert.assertNotNull(registry.getViewDescriptor("view1"));
    Assert.assertNotNull(registry.getViewDescriptor("view2"));

    Assert.assertNull("Should return null when viewName not found", registry.getViewDescriptor("bogus"));

    try {
        registry.getViewDescriptor("bogusView");
        Assert.fail("Should have thrown BeanNotOfRequiredTypeException");
    }
    catch (BeanNotOfRequiredTypeException e) {
        //do nothing, test succeeded
    }

}
项目:spring-richclient    文件:BeanFactoryViewDescriptorRegistryTests.java   
/**
 * Test method for {@link BeanFactoryViewDescriptorRegistry#getViewDescriptor(java.lang.String)}.
 */
public final void testGetViewDescriptor() {

    BeanFactoryViewDescriptorRegistry registry = new BeanFactoryViewDescriptorRegistry();
    StaticApplicationContext appCtx = new StaticApplicationContext();
    registry.setApplicationContext(appCtx);

    MutablePropertyValues mpv = new MutablePropertyValues();
    mpv.addPropertyValue("viewClass", NullView.class);
    appCtx.registerSingleton("view1", DefaultViewDescriptor.class, mpv);
    appCtx.registerSingleton("view2", DefaultViewDescriptor.class, mpv);
    appCtx.registerSingleton("bogusView", String.class);

    Assert.assertNotNull(registry.getViewDescriptor("view1"));
    Assert.assertNotNull(registry.getViewDescriptor("view2"));

    Assert.assertNull("Should return null when viewName not found", registry.getViewDescriptor("bogus"));

    try {
        registry.getViewDescriptor("bogusView");
        Assert.fail("Should have thrown BeanNotOfRequiredTypeException");
    }
    catch (BeanNotOfRequiredTypeException e) {
        //do nothing, test succeeded
    }

}