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

项目:cas-5.1.0    文件:SamlIdPConfiguration.java   
@Bean
public MetadataResolver casSamlIdPMetadataResolver() {
    try {
        final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp();
        final ResourceBackedMetadataResolver resolver = new ResourceBackedMetadataResolver(
                ResourceHelper.of(new FileSystemResource(idp.getMetadata().getMetadataFile())));
        resolver.setParserPool(this.openSamlConfigBean.getParserPool());
        resolver.setFailFastInitialization(idp.getMetadata().isFailFast());
        resolver.setRequireValidMetadata(idp.getMetadata().isRequireValidMetadata());
        resolver.setId(idp.getEntityId());
        resolver.initialize();
        return resolver;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
项目:cas-5.1.0    文件:AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java   
@Bean
public PFAuth azureAuthenticatorInstance() {
    try {
        final MultifactorAuthenticationProperties.Azure azure = casProperties.getAuthn().getMfa().getAzure();
        final File cfg = new File(azure.getConfigDir());
        if (!cfg.exists() || !cfg.isDirectory()) {
            throw new FileNotFoundException(cfg.getAbsolutePath() + " does not exist or is not a directory");
        }
        final PFAuth pf = new PFAuth();
        pf.setDebug(true);
        pf.setAllowInternationalCalls(azure.isAllowInternationalCalls());

        final String dir = StringUtils.appendIfMissing(azure.getConfigDir(), "/");
        pf.initialize(dir, azure.getPrivateKeyPassword());
        return pf;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
项目:cas-5.1.0    文件:DuoSecurityAuthenticationEventExecutionPlanConfiguration.java   
@RefreshScope
@Bean
public AuthenticationHandler duoAuthenticationHandler() {
    final DuoAuthenticationHandler h;
    final List<MultifactorAuthenticationProperties.Duo> duos = casProperties.getAuthn().getMfa().getDuo();
    if (!duos.isEmpty()) {
        final String name = duos.get(0).getName();
        if (duos.size() > 1) {
            LOGGER.debug("Multiple Duo Security providers are available; Duo authentication handler is named after [{}]", name);
        }
        h = new DuoAuthenticationHandler(name, servicesManager, duoPrincipalFactory(), duoMultifactorAuthenticationProvider());
    } else {
        h = new DuoAuthenticationHandler(StringUtils.EMPTY, servicesManager, duoPrincipalFactory(), duoMultifactorAuthenticationProvider());
        throw new BeanCreationException("No configuration/settings could be found for Duo Security. Review settings and ensure the correct syntax is used");
    }
    return h;
}
项目:cas-5.1.0    文件:GraphicalUserAuthenticationConfiguration.java   
@Bean
@ConditionalOnMissingBean(name = "userGraphicalAuthenticationRepository")
public UserGraphicalAuthenticationRepository userGraphicalAuthenticationRepository() {

    final GraphicalUserAuthenticationProperties gua = casProperties.getAuthn().getGua();
    if (StringUtils.isNotBlank(gua.getResource().getLocation())) {
        return new StaticUserGraphicalAuthenticationRepository();
    }

    if (StringUtils.isNotBlank(gua.getLdap().getLdapUrl())
            && StringUtils.isNotBlank(gua.getLdap().getUserFilter())
            && StringUtils.isNotBlank(gua.getLdap().getBaseDn())
            && StringUtils.isNotBlank(gua.getLdap().getImageAttribute())) {
        return new LdapUserGraphicalAuthenticationRepository();
    }

    throw new BeanCreationException("A repository instance must be configured to locate user-defined graphics");

}
项目:cas-5.1.0    文件:SurrogateAuthenticationConfiguration.java   
@RefreshScope
@ConditionalOnMissingBean(name = "surrogateAuthenticationService")
@Bean
public SurrogateAuthenticationService surrogateAuthenticationService() {
    try {
        final SurrogateAuthenticationProperties su = casProperties.getAuthn().getSurrogate();
        if (su.getJson().getConfig().getLocation() != null) {
            LOGGER.debug("Using JSON resource [{}] to locate surrogate accounts", su.getJson().getConfig().getLocation());
            return new JsonResourceSurrogateAuthenticationService(su.getJson().getConfig().getLocation());
        }
        if (StringUtils.hasText(su.getLdap().getLdapUrl()) && StringUtils.hasText(su.getLdap().getSearchFilter())
                && StringUtils.hasText(su.getLdap().getBaseDn()) && StringUtils.hasText(su.getLdap().getMemberAttributeName())) {
            LOGGER.debug("Using LDAP [{}] with baseDn [{}] to locate surrogate accounts",
                    su.getLdap().getLdapUrl(), su.getLdap().getBaseDn());
            final ConnectionFactory factory = Beans.newLdaptivePooledConnectionFactory(su.getLdap());
            return new LdapSurrogateUsernamePasswordService(factory, su.getLdap());
        }

        final Map<String, Set> accounts = new LinkedHashMap<>();
        su.getSimple().getSurrogates().forEach((k, v) -> accounts.put(k, StringUtils.commaDelimitedListToSet(v)));
        LOGGER.debug("Using accounts [{}] for surrogate authentication", accounts);
        return new SimpleSurrogateAuthenticationService(accounts);
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
项目:composed-task-runner    文件:ComposedRunnerVisitorTests.java   
@Test
public void failedStepTransitionWithDuplicateTaskNameTest() {
    try {
        setupContextForGraph("failedStep 'FAILED' -> BBB  && CCC && BBB && EEE");
    }
    catch (BeanCreationException bce) {
        assertEquals(TaskValidationException.class,
                bce.getRootCause().getClass());
        assertEquals("Problems found when validating 'failedStep " +
                        "'FAILED' -> BBB  && CCC && BBB && EEE': " +
                        "[166E:(pos 38): duplicate app name. Use a " +
                        "label to ensure uniqueness]",
                bce.getRootCause().getMessage());
    }

}
项目:composed-task-runner    文件:ComposedRunnerVisitorTests.java   
@Test
public void successStepTransitionWithDuplicateTaskNameTest() {
    try {
        setupContextForGraph("AAA 'FAILED' -> BBB  * -> CCC && BBB && EEE");
    }
    catch (BeanCreationException bce) {
        assertEquals(TaskValidationException.class,
                bce.getRootCause().getClass());
        assertEquals("Problems found when validating 'AAA 'FAILED' -> " +
                        "BBB  * -> CCC && BBB && EEE': [166E:(pos 33): " +
                        "duplicate app name. Use a label to ensure " +
                        "uniqueness]",
                bce.getRootCause().getMessage());
    }

}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
 * invoking their {@code postProcessMergedBeanDefinition} methods.
 * @param mbd the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @throws BeansException if any post-processing failed
 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
 */
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
        throws BeansException {

    try {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }
    catch (Exception ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Post-processing failed of bean type [" + beanType + "] failed", ex);
    }
}
项目:lams    文件:AbstractBeanFactory.java   
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} else
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
    if (!mbd.isSingleton()) {
        return null;
    }
    try {
        FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
        return getTypeForFactoryBean(factoryBean);
    }
    catch (BeanCreationException ex) {
        // Can only happen when getting a FactoryBean.
        if (logger.isDebugEnabled()) {
            logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex);
        }
        onSuppressedException(ex);
        return null;
    }
}
项目:circus-train    文件:VacuumTool.java   
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(VacuumTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printVacuumToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    throw e;
  }
}
项目:circus-train    文件:FilterTool.java   
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(FilterTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printFilterToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    throw e;
  }
}
项目:lams    文件:BeanDefinitionValueResolver.java   
/**
 * Resolve a reference to another bean in the factory.
 */
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    try {
        String refName = ref.getBeanName();
        refName = String.valueOf(evaluate(refName));
        if (ref.isToParent()) {
            if (this.beanFactory.getParentBeanFactory() == null) {
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Can't resolve reference to bean '" + refName +
                        "' in parent factory: no parent factory available");
            }
            return this.beanFactory.getParentBeanFactory().getBean(refName);
        }
        else {
            Object bean = this.beanFactory.getBean(refName);
            this.beanFactory.registerDependentBean(refName, this.beanName);
            return bean;
        }
    }
    catch (BeansException ex) {
        throw new BeanCreationException(
                this.beanDefinition.getResourceDescription(), this.beanName,
                "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
    }
}
项目:azure-spring-boot    文件:MediaServicesAutoConfigurationTest.java   
private void createAndFailWithCause(String cause) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(MediaServicesAutoConfiguration.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getCause().toString()).contains(cause);
    }
}
项目:azure-spring-boot    文件:DocumentDBPropertiesTest.java   
@Test
public void emptySettingNotAllowed() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object 'azure.documentdb' on field 'uri': rejected value [null];");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object 'azure.documentdb' on field 'key': rejected value [null];");
    }
}
项目:azure-spring-boot    文件:ServiceBusPropertiesTest.java   
@Test
public void connectionStringIsNull() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object 'azure.servicebus' on field 'connectionString': "
                        + "rejected value [null];");
    }
}
项目:azure-spring-boot    文件:ServiceBusAutoConfigurationTest.java   
private void verifyBeanCreationException(String message, Class<?> beanClass) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        Exception exception = null;
        try {
            context.register(ServiceBusAutoConfiguration.class);
            context.refresh();
            context.getBean(beanClass);
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception.getMessage()).contains(message);
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
    }
}
项目:azure-spring-boot    文件:StorageAutoConfigurationTest.java   
@Test
public void createStorageAccountWithInvalidConnectionString() {
    System.setProperty(CONNECTION_STRING_PROPERTY, INVALID_CONNECTION_STRING);

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(StorageAutoConfiguration.class);
        context.refresh();

        CloudStorageAccount cloudStorageAccount = null;
        try {
            cloudStorageAccount = context.getBean(CloudStorageAccount.class);
        } catch (Exception e) {
            assertThat(e).isExactlyInstanceOf(BeanCreationException.class);
        }

        assertThat(cloudStorageAccount).isNull();
    }

    System.clearProperty(CONNECTION_STRING_PROPERTY);
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                }
            }, getAccessControlContext());
        }
        else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}
项目:shibboleth-idp-oidc-extension    文件:BasicJWKCredentialFactoryBean.java   
/** {@inheritDoc} */
@Override
protected BasicJWKCredential doCreateInstance() throws Exception {

    if (jwkResource == null) {
        log.error("{}: No JWK credential provided", getConfigDescription());
        throw new BeanCreationException("No JWK credential provided");
    }
    JWK jwk = null;
    BasicJWKCredential jwkCredential = null;
    try (InputStream is = jwkResource.getInputStream()) {
        jwk = JWK.parse(new String(ByteStreams.toByteArray(is)));
        jwkCredential = new BasicJWKCredential();
        if (jwk.getKeyType() == KeyType.EC || jwk.getKeyType() == KeyType.RSA) {
            if (jwk.isPrivate()) {
                jwkCredential.setPrivateKey(((AssymetricJWK) jwk).toPrivateKey());
            }
            jwkCredential.setPublicKey(((AssymetricJWK) jwk).toPublicKey());
        } else if (jwk.getKeyType() == KeyType.OCT) {
            jwkCredential.setSecretKey(((OctetSequenceKey) jwk).toSecretKey());
        } else {
            throw new FatalBeanException("Unsupported KeyFile at " + jwkResource.getDescription());
        }
    } catch (IOException | ParseException | JOSEException e) {
        log.error("{}: Could not decode KeyFile at {}: {}", 
                getConfigDescription(), jwkResource.getDescription(), e);
        throw new FatalBeanException("Could not decode provided KeyFile " + jwkResource.getDescription(), e);
    }
    jwkCredential.setUsageType(getUsageType(jwk));
    jwkCredential.setEntityId(getEntityID());
    jwkCredential.setAlgorithm(jwk.getAlgorithm());
    jwkCredential.setKid(jwk.getKeyID());
    final List<String> keyNames = getKeyNames();
    if (keyNames != null) {
        jwkCredential.getKeyNames().addAll(keyNames);
    }
    return jwkCredential;
}
项目:dubbox-hystrix    文件:ConfigTest.java   
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
项目:oasp-tutorial-sources    文件:BeansBatchConfig.java   
/**
 * This method is creating jobLauncher bean
 *
 * @return SimpleJobLauncher
 */
@Bean
@DependsOn("jobRepository")
public JobLauncherWithAdditionalRestartCapabilities jobLauncher() {

  this.jobLauncher = new JobLauncherWithAdditionalRestartCapabilities();

  try {
    this.jobLauncher.setJobRepository(this.jobRepository.getObject());
  } catch (Exception e) {
    throw new BeanCreationException("Could not create BatchJobOperator", e);
  }

  return this.jobLauncher;
}
项目:lams    文件:StaticListableBeanFactory.java   
@Override
public Object getBean(String name) throws BeansException {
    String beanName = BeanFactoryUtils.transformedBeanName(name);
    Object bean = this.beans.get(beanName);

    if (bean == null) {
        throw new NoSuchBeanDefinitionException(beanName,
                "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
    }

    // Don't let calling code try to dereference the
    // bean factory if the bean isn't a factory
    if (BeanFactoryUtils.isFactoryDereference(name) && !(bean instanceof FactoryBean)) {
        throw new BeanIsNotAFactoryException(beanName, bean.getClass());
    }

    if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
        try {
            return ((FactoryBean<?>) bean).getObject();
        }
        catch (Exception ex) {
            throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
        }
    }
    else {
        return bean;
    }
}
项目:cas-5.1.0    文件:CoreWsSecuritySecurityTokenServiceConfiguration.java   
@RefreshScope
@Bean
public Provider transportSTSProviderBean() {
    try {
        final SecurityTokenServiceProvider provider = new SecurityTokenServiceProvider();
        provider.setIssueOperation(transportIssueDelegate());
        provider.setValidateOperation(transportValidateDelegate());
        return provider;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
项目:cas-5.1.0    文件:MongoDbCloudConfigBootstrapConfiguration.java   
@Bean
public MongoClientOptions mongoClientOptions() {
    try {
        final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
        bean.setSocketTimeout(TIMEOUT);
        bean.setConnectTimeout(TIMEOUT);
        bean.afterPropertiesSet();
        return bean.getObject();
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
项目:lams    文件:PersistenceAnnotationBeanPostProcessor.java   
@Override
public PropertyValues postProcessPropertyValues(
        PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

    InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass());
    try {
        metadata.inject(bean, beanName, pvs);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of persistence dependencies failed", ex);
    }
    return pvs;
}
项目:composed-task-runner    文件:ComposedRunnerVisitorTests.java   
@Test
public void testSequentialTransitionAndSplitFailedInvalid() {
    try {
        setupContextForGraph("AAA && failedStep 'FAILED' -> EEE '*' -> FFF && <BBB||CCC> && DDD");
    }
    catch (BeanCreationException bce) {
        validateInvalidFlowWildCard(bce);
    }
}
项目:composed-task-runner    文件:ComposedRunnerVisitorTests.java   
@Test
public void testSuccessBasicTransitionWithSequence() {
    try {
        setupContextForGraph("AAA 'FAILED' -> BBB * -> CCC && DDD && EEE");
    }
    catch (BeanCreationException bce) {
        validateInvalidFlowWildCard(bce);
    }
}
项目:apollo-custom    文件:JavaConfigAnnotationTest.java   
@Test(expected = BeanCreationException.class)
public void testApolloConfigChangeListenerWithWrongParamType() throws Exception {
  Config applicationConfig = mock(Config.class);

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig);

  getBean(TestApolloConfigChangeListenerBean2.class, AppConfig4.class);
}
项目:dubbocloud    文件:ConfigTest.java   
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
项目:zipkin-sparkstreaming    文件:ZipkinStorageConsumerAutoConfigurationTest.java   
/** fail fast is default, which helps discover storage errors before the job runs */
@Test public void failFast() {
  addEnvironment(context,
      "zipkin.storage.type:elasticsearch",
      "zipkin.storage.elasticsearch.hosts:http://host1:9200"
  );
  context.register(PropertyPlaceholderAutoConfiguration.class,
      ZipkinStorageConsumerAutoConfiguration.class);

  thrown.expect(BeanCreationException.class);
  context.refresh();
}
项目:spring-cloud-vault-connector    文件:AbstractCloudConfigServiceTest.java   
@Test(expected = BeanCreationException.class)
public void cloudConnectorWithoutServiceNameSpecified_TwoServiceExist_byId() {
    ApplicationContext testContext = getTestApplicationContextWithoutServiceId(
            createService("my-service"), createService("my-service-2"));

    testContext.getBean(getConnectorType());
}
项目:EatDubbo    文件:ConfigTest.java   
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
项目:cfsummiteu2017    文件:PlatformRepositoryImpl.java   
@Override
public void addPlatform(Platform platform, PlatformService platformService) {
    if (platformServices.get(platform) == null)
        platformServices.put(platform, platformService);
    else
        throw new BeanCreationException("Cannot add multiple instances of platform service to PlatformRepository");
}
项目:gemini.blueprint    文件:ManagedServiceFactoryFactoryBean.java   
private void registerService(String pid, Object bean) {
    OsgiServiceFactoryBean exporter = createExporter(pid, bean);
    serviceExporters.put(pid, exporter);
    try {
        serviceRegistrations.add(exporter.getObject());
    } catch (Exception ex) {
        throw new BeanCreationException("Cannot publish bean for pid " + pid, ex);
    }
}
项目:dubbo2    文件:ConfigTest.java   
@Test
public void testMultiProtocolError() {
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/multi-protocol-error.xml");
        ctx.start();
        ctx.stop();
        ctx.close();
    } catch (BeanCreationException e) {
        assertTrue(e.getMessage().contains("Found multi-protocols"));
    }
}
项目:gemini.blueprint    文件:ManagedServiceFactoryFactoryBean.java   
private OsgiServiceFactoryBean createExporter(String beanName, Object bean) {
    OsgiServiceFactoryBean exporter = new OsgiServiceFactoryBean();
    exporter.setInterfaceDetector(detector);
    exporter.setBeanClassLoader(classLoader);
    exporter.setBeanName(beanName);
    exporter.setBundleContext(bundleContext);
    exporter.setExportContextClassLoader(ccl);
    exporter.setInterfaces(interfaces);
    exporter.setListeners(listeners);
    exporter.setTarget(bean);

    // add properties
    Properties props = new Properties();
    if (serviceProperties != null) {
        props.putAll(serviceProperties);
    }
    // add the service pid (to be able to identify the bean instance)
    props.put(Constants.SERVICE_PID, beanName);
    exporter.setServiceProperties(props);

    try {
        exporter.afterPropertiesSet();
    } catch (Exception ex) {
        throw new BeanCreationException("Cannot publish bean for pid " + beanName, ex);
    }
    return exporter;
}
项目:apollo-custom    文件:XMLConfigAnnotationTest.java   
@Test(expected = BeanCreationException.class)
public void testApolloConfigWithWrongFieldType() throws Exception {
  Config applicationConfig = mock(Config.class);

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig);

  getBean("spring/XmlConfigAnnotationTest2.xml", TestApolloConfigBean2.class);
}
项目:lams    文件:AutowiredAnnotationBeanPostProcessor.java   
/**
 * 'Native' processing method for direct calls with an arbitrary target instance,
 * resolving all of its fields and methods which are annotated with {@code @Autowired}.
 * @param bean the target instance to process
 * @throws BeansException if autowiring failed
 */
public void processInjection(Object bean) throws BeansException {
    Class<?> clazz = bean.getClass();
    InjectionMetadata metadata = findAutowiringMetadata(clazz.getName(), clazz);
    try {
        metadata.inject(bean, null, null);
    }
    catch (Throwable ex) {
        throw new BeanCreationException("Injection of autowired dependencies failed for class [" + clazz + "]", ex);
    }
}
项目:apollo-custom    文件:JavaConfigAnnotationTest.java   
@Test(expected = BeanCreationException.class)
public void testApolloConfigWithWrongFieldType() throws Exception {
  Config applicationConfig = mock(Config.class);

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig);

  getBean(TestApolloConfigBean2.class, AppConfig2.class);
}
项目:azure-spring-boot    文件:AADAuthenticationFilterPropertiesTest.java   
@Test
public void emptySettingsNotAllowed() {
    System.setProperty(Constants.CLIENT_ID_PROPERTY, "");
    System.setProperty(Constants.CLIENT_SECRET_PROPERTY, "");

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'clientId': rejected value []");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'clientSecret': rejected value []");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'activeDirectoryGroups': rejected value [null]");
    }

    System.clearProperty(Constants.CLIENT_ID_PROPERTY);
    System.clearProperty(Constants.CLIENT_SECRET_PROPERTY);
}