Example usage for org.springframework.context ApplicationContext getBeansOfType

List of usage examples for org.springframework.context ApplicationContext getBeansOfType

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext getBeansOfType.

Prototype

<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;

Source Link

Document

Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.

Usage

From source file:net.javacrumbs.springws.test.xml.SimpleSchemaBasedTest.java

@Test
public void testMinimalSchema() {
    ApplicationContext context = new ClassPathXmlApplicationContext("context/minimal-schema-based-context.xml");
    MockWebServiceMessageSender sender = (MockWebServiceMessageSender) context.getBean("mock-sender");
    assertNotNull(sender);/*from   w  w w. j  a v a 2  s .  c  om*/
    assertTrue(sender.isAutowireRequestProcessors());

    List<RequestProcessor> requestProcessors = sender.getRequestProcessors();
    assertNotNull(requestProcessors);

    assertEquals(2, requestProcessors.size());

    XmlCompareRequestValidator xmlCompareValidator = (XmlCompareRequestValidator) requestProcessors.get(0);
    assertTrue(xmlCompareValidator.isIgnoreWhitespace());
    PayloadRootBasedResourceLookup controlResourceLookup = (PayloadRootBasedResourceLookup) xmlCompareValidator
            .getControlResourceLookup();
    assertEquals("request.xml", controlResourceLookup.getPathSuffix());
    assertEquals("mock-xml/", controlResourceLookup.getPathPrefix());
    assertFalse(controlResourceLookup.isPrependUri());
    assertEquals(XsltTemplateProcessor.class, controlResourceLookup.getTemplateProcessor().getClass());

    DefaultResponseGenerator generator = (DefaultResponseGenerator) requestProcessors.get(1);
    PayloadRootBasedResourceLookup resourceLookup = (PayloadRootBasedResourceLookup) generator
            .getResourceLookup();
    assertEquals("response.xml", resourceLookup.getPathSuffix());
    assertEquals("mock-xml/", resourceLookup.getPathPrefix());
    assertFalse(resourceLookup.isPrependUri());
    assertEquals(XsltTemplateProcessor.class, resourceLookup.getTemplateProcessor().getClass());

    assertEquals(1, context.getBeansOfType(MockMessageSenderInjector.class).size());

}

From source file:net.javacrumbs.springws.test.xml.SimpleSchemaBasedTest.java

@Test
public void testSimpleSchema() {
    ApplicationContext context = new ClassPathXmlApplicationContext("context/simple-schema-based-context.xml");
    MockWebServiceMessageSender sender = (MockWebServiceMessageSender) context.getBean("mock-sender");
    assertNotNull(sender);//from  ww w  .j  a  va2s . c  o  m
    assertFalse(sender.isAutowireRequestProcessors());

    List<RequestProcessor> requestProcessors = sender.getRequestProcessors();
    assertNotNull(requestProcessors);

    assertEquals(3, requestProcessors.size());

    XmlCompareRequestValidator xmlCompareValidator = (XmlCompareRequestValidator) requestProcessors.get(0);
    assertFalse(xmlCompareValidator.isIgnoreWhitespace());
    PayloadRootBasedResourceLookup controlResourceLookup = (PayloadRootBasedResourceLookup) xmlCompareValidator
            .getControlResourceLookup();
    assertEquals("request.xml", controlResourceLookup.getPathSuffix());
    assertEquals("mock/", controlResourceLookup.getPathPrefix());
    assertArrayEquals(new String[] { "//ns:from", "//ns:to" },
            controlResourceLookup.getDiscriminatorsMap().get("getFlightsRequest"));
    assertTrue(controlResourceLookup.isPrependUri());
    assertEquals(FreeMarkerTemplateProcessor.class, controlResourceLookup.getTemplateProcessor().getClass());

    SchemaRequestValidator schemaValidator = (SchemaRequestValidator) requestProcessors.get(1);
    assertEquals(1, schemaValidator.getSchemas().length);

    DefaultResponseGenerator generator = (DefaultResponseGenerator) requestProcessors.get(2);
    PayloadRootBasedResourceLookup resourceLookup = (PayloadRootBasedResourceLookup) generator
            .getResourceLookup();
    assertEquals("response.xml", resourceLookup.getPathSuffix());
    assertEquals("mock/", resourceLookup.getPathPrefix());
    assertArrayEquals(new String[] { "//ns:from", "//ns:to" },
            resourceLookup.getDiscriminatorsMap().get("getFlightsRequest"));
    assertTrue(resourceLookup.isPrependUri());
    assertEquals(FreeMarkerTemplateProcessor.class, resourceLookup.getTemplateProcessor().getClass());

    assertEquals(0, context.getBeansOfType(MockMessageSenderInjector.class).size());

    assertEquals(1, sender.getInterceptors().size());

}

From source file:com.quancheng.saluki.springsupport.internal.ServiceBean.java

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    synchronized (lock) {
        if (initialled) {
            return;
        } else {// w ww. j ava2  s . c om
            ApplicationContext applicationContext = event.getApplicationContext();
            Map<String, ServiceBean> instances = applicationContext.getBeansOfType(ServiceBean.class);
            if (!instances.isEmpty()) {
                ConfigBean configBean = applicationContext.getBean(ConfigBean.class);
                this.thrallProperties = configBean;
                RpcServiceConfig rpcSerivceConfig = new RpcServiceConfig();
                this.addRegistyAddress(rpcSerivceConfig);
                rpcSerivceConfig.setApplication(thrallProperties.getApplication());
                this.addHostAndPort(rpcSerivceConfig);
                rpcSerivceConfig.setMonitorinterval(thrallProperties.getMonitorinterval());
                for (Map.Entry<String, ServiceBean> entry : instances.entrySet()) {
                    ServiceBean serviceBean = entry.getValue();
                    rpcSerivceConfig.addServiceDefinition(serviceBean.getServiceName(), serviceBean.getGroup(),
                            serviceBean.getVersion(), serviceBean.getRef());
                }
                this.rpcService = rpcSerivceConfig;
                initialled = true;
                rpcSerivceConfig.export();
            }
        }

    }

}

From source file:hudson.security.SecurityRealm.java

/**
 * Picks up the instance of the given type from the spring context.
 * If there are multiple beans of the same type or if there are none,
 * this method treats that as an {@link IllegalArgumentException}.
 *
 * This method is intended to be used to pick up a Acegi object from
 * spring once the bean definition file is parsed.
 *//*from  w  w w  .  jav a  2s  .c  om*/
public static <T> T findBean(Class<T> type, ApplicationContext context) {
    Map m = context.getBeansOfType(type);
    switch (m.size()) {
    case 0:
        throw new IllegalArgumentException("No beans of " + type + " are defined");
    case 1:
        return type.cast(m.values().iterator().next());
    default:
        throw new IllegalArgumentException("Multiple beans of " + type + " are defined: " + m);
    }
}

From source file:io.seldon.api.state.PredictionAlgorithmStore.java

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    StringBuilder builder = new StringBuilder("Available algorithms: \n");
    for (PredictionAlgorithm inc : applicationContext.getBeansOfType(PredictionAlgorithm.class).values()) {
        builder.append('\t');
        builder.append(inc.getClass());//from w w w.j a v  a2s  .  c  om
        builder.append('\n');
    }
    builder.append("Available feature transformers: \n");
    for (FeatureTransformer f : applicationContext.getBeansOfType(FeatureTransformer.class).values()) {
        builder.append('\t');
        builder.append(f.getClass());
        builder.append('\n');
    }
    logger.info(builder.toString());

}

From source file:org.acegisecurity.ui.ExceptionTranslationFilter.java

/**
 * Introspects the <code>Applicationcontext</code> for the single instance
 * of {@link AccessDeniedHandler}. If found invoke
 * setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) method by
 * providing the found instance of accessDeniedHandler as a method
 * parameter. If more than one instance of <code>AccessDeniedHandler</code>
 * is found, the method throws <code>IllegalStateException</code>.
 * /*from  w w  w  .j  a v a2s  . c  o  m*/
 * @param applicationContext to locate the instance
 */
private void autoDetectAnyAccessDeniedHandlerAndUseIt(ApplicationContext applicationContext) {
    Map map = applicationContext.getBeansOfType(AccessDeniedHandler.class);
    if (map.size() > 1) {
        throw new IllegalArgumentException(
                "More than one AccessDeniedHandler beans detected please refer to the one using "
                        + " [ accessDeniedBeanRef  ] " + "attribute");
    } else if (map.size() == 1) {
        AccessDeniedHandler handler = (AccessDeniedHandlerImpl) map.values().iterator().next();
        setAccessDeniedHandler(handler);
    } else {
        // create and use the default one specified as an instance variable.
        accessDeniedHandler = new AccessDeniedHandlerImpl();
    }

}

From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java

/**
 * Introspects the <code>Applicationcontext</code> for the single instance
 * of {@link AccessDeniedHandler}. If found invoke
 * setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) method by
 * providing the found instance of accessDeniedHandler as a method
 * parameter. If more than one instance of <code>AccessDeniedHandler</code>
 * is found, the method throws <code>IllegalStateException</code>.
 * //from  w  ww  .j av  a2 s . co m
 * @param applicationContext to locate the instance
 */
private void autoDetectAndUseAnyUserDetailsService(ApplicationContext applicationContext) {
    Map map = applicationContext.getBeansOfType(UserDetailsService.class);
    if (map.size() > 1) {
        throw new IllegalArgumentException(
                "More than one UserDetailsService beans detected please refer to the one using "
                        + " [ principalRepositoryBeanRef  ] " + "attribute");
    } else if (map.size() == 1) {
        setUserDetailsService((UserDetailsService) map.values().iterator().next());
    }
}

From source file:org.apache.archiva.rest.services.AbstractRestService.java

protected <T> Map<String, T> getBeansOfType(ApplicationContext applicationContext, Class<T> clazz) {
    //TODO do some caching here !!!
    // olamy : with plexus we get only roleHint
    // as per convention we named spring bean role#hint remove role# if exists
    Map<String, T> springBeans = applicationContext.getBeansOfType(clazz);

    Map<String, T> beans = new HashMap<>(springBeans.size());

    for (Map.Entry<String, T> entry : springBeans.entrySet()) {
        String key = StringUtils.contains(entry.getKey(), '#')
                ? StringUtils.substringAfterLast(entry.getKey(), "#")
                : entry.getKey();/*from   w  w  w .ja  v a2s .c o  m*/
        beans.put(key, entry.getValue());
    }
    return beans;
}