Example usage for org.springframework.context ApplicationContext getBeanDefinitionNames

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

Introduction

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

Prototype

String[] getBeanDefinitionNames();

Source Link

Document

Return the names of all beans defined in this factory.

Usage

From source file:de.contentreich.instrumentation.SpringBeansHelper.java

public List<String[]> getSpringBeans(ApplicationContext appContext, String parentId) {
    logger.debug("Get spring beans for context " + parentId);
    ArrayList<String[]> beans = new ArrayList<String[]>();
    String[] names = appContext.getBeanDefinitionNames();
    for (int i = 0; i < names.length; i++) {
        String beanName = names[i];
        DefaultListableBeanFactory beanFactory = getBeanFactory(appContext);
        Class clazz = getBeanClass(beanName, beanFactory);
        // DefaultListableBeanFactory beanFactory = (appContext instanceof DefaultListableBeanFactory) ? (DefaultListableBeanFactory) appContext : null;
        if (clazz != null && beanFactory != null) { // Not abstract
            BeanDefinition def = beanFactory.getBeanDefinition(beanName);
            if (!(def.isPrototype() || def.isLazyInit())) {
                Object bean = appContext.getBean(beanName);
                if (holdsChildApplicationContext(bean)) {
                    // Semantically not perfect but ok ;)
                    clazz = getApplicationContext(bean).getClass();
                }/*from   w  w  w .  ja va  2 s  .  c  o  m*/
            }
            String[] beanEntry = new String[] { beanName, clazz.getName(), parentId };
            beans.add(beanEntry);
        }
    }
    Collections.sort(beans, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            String s1 = ((String[]) o1)[0];
            String s2 = ((String[]) o2)[0];
            return s1.compareTo(s2);
        }

    });
    logger.debug("Got " + beans.size() + " spring beans");
    return beans;
}

From source file:io.gravitee.gateway.repository.plugins.RepositoryPluginHandler.java

private void registerRepositoryDefinitions(Repository repository, ApplicationContext repoApplicationContext) {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();/*w  ww. ja  va2 s  .  c  o  m*/

    String[] beanNames = repoApplicationContext.getBeanDefinitionNames();
    for (String beanName : beanNames) {
        Object repositoryClassInstance = repoApplicationContext.getBean(beanName);
        if ((beanName.endsWith("Repository") || beanName.endsWith("Manager"))
                && !repository.getClass().equals(repositoryClassInstance.getClass())) {
            Class<?> repositoryObjectClass = repositoryClassInstance.getClass();
            if (repositoryObjectClass.getInterfaces().length > 0) {
                Class<?> repositoryItfClass = repositoryObjectClass.getInterfaces()[0];
                LOGGER.debug("Register {} [{}] in gateway context", beanName, repositoryItfClass);
                beanFactory.registerSingleton(repositoryItfClass.getName(), repositoryClassInstance);
            }
        }
    }
}

From source file:org.solmix.runtime.support.spring.SpringConfigurer.java

private void initWildcardDefinitionMap() {
    if (null != appContexts) {
        for (ApplicationContext appContext : appContexts) {
            for (String n : appContext.getBeanDefinitionNames()) {
                if (isWildcardBeanName(n)) {
                    AutowireCapableBeanFactory bf = appContext.getAutowireCapableBeanFactory();
                    BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) bf;
                    BeanDefinition bd = bdr.getBeanDefinition(n);
                    String className = bd.getBeanClassName();
                    if (null != className) {
                        String orig = n;
                        if (n.charAt(0) == '*') {
                            //old wildcard
                            n = "." + n.replaceAll("\\.", "\\.");
                        }// www .j a  v  a2s  .co m
                        try {
                            Matcher matcher = Pattern.compile(n).matcher("");
                            List<MatcherHolder> m = wildCardBeanDefinitions.get(className);
                            if (m == null) {
                                m = new ArrayList<MatcherHolder>();
                                wildCardBeanDefinitions.put(className, m);
                            }
                            MatcherHolder holder = new MatcherHolder(orig, matcher);
                            m.add(holder);
                        } catch (PatternSyntaxException npe) {
                            //not a valid patter, we'll ignore
                        }
                    } else {
                        LOG.warn("Wildcars with not class {}", n);
                    }
                }
            }
        }
    }
}

From source file:io.gravitee.management.repository.plugins.RepositoryPluginHandler.java

private void registerRepositoryDefinitions(Repository repository, ApplicationContext repoApplicationContext) {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();/*from w  ww  .  ja v  a 2 s  .  c o m*/

    String[] beanNames = repoApplicationContext.getBeanDefinitionNames();
    for (String beanName : beanNames) {
        Object repositoryClassInstance = repoApplicationContext.getBean(beanName);
        Class<?> repositoryObjectClass = repositoryClassInstance.getClass();
        if ((beanName.endsWith("Repository")
                || (beanName.endsWith("Manager") && !beanName.endsWith("TransactionManager")))
                && !repository.getClass().equals(repositoryClassInstance.getClass())) {
            if (repositoryObjectClass.getInterfaces().length > 0) {
                Class<?> repositoryItfClass = repositoryObjectClass.getInterfaces()[0];
                LOGGER.debug("Set proxy target for {} [{}]", beanName, repositoryItfClass);
                try {
                    Object proxyRepository = beanFactory.getBean(repositoryItfClass);
                    if (proxyRepository instanceof AbstractProxy) {
                        AbstractProxy proxy = (AbstractProxy) proxyRepository;
                        proxy.setTarget(repositoryClassInstance);
                    }
                } catch (NoSuchBeanDefinitionException nsbde) {
                    LOGGER.debug("Unable to proxify {} [{}]", beanName, repositoryItfClass);
                }
            }
        } else if (beanName.endsWith("TransactionManager")) {
            beanFactory.registerSingleton(beanName, repositoryClassInstance);
        }
    }
}

From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java

@Override
protected Set<Class> findActions() {
    Set<Class> classes = new HashSet<Class>();

    final ApplicationContext ac = this.applicationContext;
    String[] beanNames = ac.getBeanDefinitionNames();
    for (String beanName : beanNames) {

        // don't care for the bean itself right now, just it's class
        Class beanClass = ac.getType(beanName);

        // first of all, check for the @Controller annotation...
        // then, if it's inside the right package (base controllers package)
        if (beanClass.isAnnotationPresent(Controller.class)
                && beanClass.getPackage().getName().startsWith(this.packageLocatorsBasePackage)) {
            // we must warn in case of a singleton scoped controller
            if (ac.isSingleton(beanName)) {
                LOG.warn(""); // TODO
            }/*from   www. j a  v a  2s . c om*/
            classes.add(beanClass);
        }

    }
    return classes;
}

From source file:org.wso2.carbon.springservices.ui.SpringServiceMaker.java

public SpringBeansData getSpringBeanNames(String springContextId, String springBeanId,
        ClassLoader bundleClassLoader) throws AxisFault {
    // Manipulation of springContext to ${RepositoryLocation}/spring

    String springContextFilePath = getFilePathFromArchiveId(springContextId);
    String springBeanFilePath = getFilePathFromArchiveId(springBeanId);
    SpringBeansData data = new SpringBeansData();
    data.setSpringContext(springContextId);

    File urlFile = new File(springBeanFilePath);

    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    ClassLoader urlCl;//www  .j  a va2s.  c  o m
    try {
        URL url = urlFile.toURL();
        urlCl = URLClassLoader.newInstance(new URL[] { url }, bundleClassLoader);

        // Save the class loader so that you can restore it later
        Thread.currentThread().setContextClassLoader(urlCl);

        ApplicationContext aCtx = GenericApplicationContextUtil
                .getSpringApplicationContext(springContextFilePath, springBeanFilePath);
        String[] beanDefintions = aCtx.getBeanDefinitionNames();
        data.setBeans(beanDefintions);
    } catch (Exception e) {
        String msg = bundle.getString("spring.cannot.load.spring.beans");
        handleException(msg, e);
    } finally {
        Thread.currentThread().setContextClassLoader(prevCl);
    }
    return data;
}

From source file:com.cassius.spring.assembly.test.common.core.SpringAssemblyTest.java

/**
 * Init Spring Context//  w ww  .j ava 2  s . co  m
 * @return the spring context
 */
private ApplicationContext getSpringContext() {
    String[] configurationLocations = ContextUtil.getContextConfiguration(this);
    MergedContextConfiguration contextConfiguration = ContextUtil.getMergedContextConfiguration(this);
    if (!contextCache.contains(contextConfiguration)) {
        ApplicationContext context = new ClassPathXmlApplicationContext(configurationLocations);
        if (logger.isInfoEnabled()) {
            logger.info(LogFormatUtil.format("@@ Init Spring Context: " + getClass().getName()));
            logger.info(LogFormatUtil.format("@@ Loaded Spring Files: ", configurationLocations));
            logger.info(LogFormatUtil.format("@@ Loaded Spring Beans: ", context.getBeanDefinitionNames()));
        }
        contextCache.put(contextConfiguration, context);
    }
    return contextCache.get(contextConfiguration);
}

From source file:com.taobao.ad.easyschedule.security.ActionSecurityBean.java

/**
 * ??BO?Annotation??Annotation?//from  www  .j a v  a2  s  . c o m
 */
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    String[] beanNames = applicationContext.getBeanDefinitionNames();
    if (beanNames == null || beanNames.length == 0) {
        System.err.println(
                "Warning: seems there are no Spring Beans defined, please double check..................");
        return;
    }
    for (String name : beanNames) {
        if (!name.endsWith("Action")) {
            continue;
        }
        Class<?> c = AopUtils.getTargetClass(applicationContext.getBean(name));
        Object bean = applicationContext.getBean(name);

        while (Proxy.isProxyClass(c) && (bean instanceof Advised)) {
            try {
                bean = ((Advised) bean).getTargetSource();
                bean = ((TargetSource) bean).getTarget();
                c = bean.getClass();
            } catch (Exception e) {
                throw new IllegalStateException("Can't initialize SecurityBean, due to:" + e.getMessage());
            }
        }
        long moduleIdDefinedInInterface = -1;
        ActionSecurity moduleAnno = AnnotationUtils.findAnnotation(c, ActionSecurity.class);
        if (moduleAnno != null) {
            moduleIdDefinedInInterface = moduleAnno.module();
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            ActionSecurity methodAnno = AnnotationUtils.findAnnotation(method, ActionSecurity.class);
            if (methodAnno != null || moduleIdDefinedInInterface != -1) {
                if (methodAnno == null) {
                    methodAnno = moduleAnno; // use interface annotation
                }
                long module = methodAnno.module() == 0 ? moduleIdDefinedInInterface : methodAnno.module();
                Module myModule = moduleIndex.get(module);
                if (myModule == null) {
                    throw new IllegalArgumentException(
                            "Found invalid module id:" + module + " in method annotation:" + method
                                    + " valid module ids are: " + moduleIndex.keySet());
                }
                if (methodAnno.enable()) {
                    myModule.addOperation(method, methodAnno, methodIndex);
                }
            }
        }
    }
    System.out.println("[ActionSecurityBean] Total " + methodIndex.size() + " methods are secured!");
}

From source file:org.xmlactions.web.conceal.HttpPager.java

public static SessionExecContext setupExecContext(ServletContext servletContext)
        throws IOException, FileUploadException {

    ApplicationContext applicationContext = getApplicationContext(servletContext);

    SessionExecContext execContext = (SessionExecContext) applicationContext
            .getBean(ActionConst.EXEC_CONTEXT_BEAN_REF);

    new CreateHandyParams(execContext);
    new CreateUserParams(execContext);

    // execContext.reset();
    RequestExecContext.set(execContext);

    // Make it available for the scope of this request.

    execContext.setApplicationContext(applicationContext);

    execContext.put(ActionConst.WEB_REAL_PATH_BEAN_REF, realPath);
    execContext.put(ActionConst.PAGE_NAMESPACE_BEAN_REF, nameSpace);

    // remove the leading slash/
    execContext.put(PagerWebConst.EXEC_CONTEXT, execContext);

    log.debug("nameSpace:" + nameSpace);
    log.debug("Real Path:" + realPath);
    log.debug("bean count:" + execContext.getApplicationContext().getBeanDefinitionCount());
    for (String beanName : applicationContext.getBeanDefinitionNames()) {
        log.debug("bean:" + beanName);
        execContext.put(beanName, applicationContext.getBean(beanName));
    }// w w w . jav a2  s .  co  m

    log.info("ExecContext size:" + execContext.size());

    return execContext;
}

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

private void addServiceDefsForSpringBeans(ApplicationContext context) {
    ConfigurableListableBeanFactory beanFactory = null;
    if (context instanceof ConfigurableApplicationContext) {
        beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory();
    }//from  ww w .j  ava2 s.  c om

    for (final String beanName : context.getBeanDefinitionNames()) {
        boolean isAbstract = false;
        if (beanFactory != null) {
            isAbstract = beanFactory.getBeanDefinition(beanName).isAbstract();
        }

        if (!isAbstract) {
            String trueName = beanName.startsWith("&") ? beanName.substring(1) : beanName;

            services.put(trueName, new SpringBeanServiceDef(trueName, context));
        }
    }
}