Example usage for org.springframework.context ApplicationContext containsBean

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

Introduction

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

Prototype

boolean containsBean(String name);

Source Link

Document

Does this bean factory contain a bean definition or externally registered singleton instance with the given name?

Usage

From source file:org.codehaus.griffon.runtime.spring.DefaultRuntimeSpringConfiguration.java

private void trySettingClassLoaderOnContextIfFoundInParent(ApplicationContext parent) {
    if (parent.containsBean(GriffonRuntimeConfigurator.CLASS_LOADER_BEAN)) {
        Object classLoader = parent.getBean(GriffonRuntimeConfigurator.CLASS_LOADER_BEAN);
        if (classLoader instanceof ClassLoader) {
            ClassLoader cl = (ClassLoader) classLoader;
            setClassLoaderOnContext(cl);
        }/* www  .j  av a  2  s. co  m*/
    }
}

From source file:org.syncope.core.scheduling.SpringBeanJobFactory.java

/**
 * An implementation of SpringBeanJobFactory that retrieves the bean from
 * the Spring context so that autowiring and transactions work.
 *
 * {@inheritDoc}/*  ww w .ja va  2 s. c o  m*/
 */
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {

    final ApplicationContext ctx = ((ConfigurableApplicationContext) schedulerContext
            .get("applicationContext"));

    // Try to re-create job bean from underlying task (useful for managing
    // failover scenarios)
    if (!ctx.containsBean(bundle.getJobDetail().getName())) {
        Long taskId = JobInstanceLoader.getTaskIdFromJobName(bundle.getJobDetail().getName());
        if (taskId != null) {
            TaskDAO taskDAO = ctx.getBean(TaskDAO.class);
            SchedTask task = taskDAO.find(taskId);

            JobInstanceLoader jobInstanceLoader = ctx.getBean(JobInstanceLoader.class);
            jobInstanceLoader.registerJob(task, task.getJobClassName(), task.getCronExpression());
        }

        Long reportId = JobInstanceLoader.getReportIdFromJobName(bundle.getJobDetail().getName());
        if (reportId != null) {
            ReportDAO reportDAO = ctx.getBean(ReportDAO.class);
            Report report = reportDAO.find(reportId);

            JobInstanceLoader jobInstanceLoader = ctx.getBean(JobInstanceLoader.class);
            jobInstanceLoader.registerJob(report);
        }
    }

    final Object job = ctx.getBean(bundle.getJobDetail().getName());
    final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(job);
    if (isEligibleForPropertyPopulation(wrapper.getWrappedInstance())) {
        final MutablePropertyValues pvs = new MutablePropertyValues();
        if (this.schedulerContext != null) {
            pvs.addPropertyValues(this.schedulerContext);
        }
        pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
        pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
        if (this.ignoredUnknownProperties == null) {
            wrapper.setPropertyValues(pvs, true);
        } else {
            for (String propName : this.ignoredUnknownProperties) {
                if (pvs.contains(propName) && !wrapper.isWritableProperty(propName)) {

                    pvs.removePropertyValue(propName);
                }
            }
            wrapper.setPropertyValues(pvs);
        }
    }
    return job;
}

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

public synchronized void configureBean(String bn, Object beanInstance, boolean checkWildcards) {

    if (null == appContexts) {
        return;/*from w  w w  .j  a  va  2s.c o m*/
    }

    if (null == bn) {
        bn = getBeanName(beanInstance);
    }

    if (null == bn) {
        return;
    }
    //configure bean with * pattern style.
    if (checkWildcards) {
        configureWithWildCard(bn, beanInstance);
    }

    final String beanName = bn;
    setBeanWiringInfoResolver(new BeanWiringInfoResolver() {
        @Override
        public BeanWiringInfo resolveWiringInfo(Object instance) {
            if (!"".equals(beanName)) {
                return new BeanWiringInfo(beanName);
            }
            return null;
        }
    });

    for (ApplicationContext appContext : appContexts) {
        if (appContext.containsBean(bn)) {
            this.setBeanFactory(appContext.getAutowireCapableBeanFactory());
        }
    }

    try {
        //this will prevent a call into the AbstractBeanFactory.markBeanAsCreated(...)
        //which saves ALL the names into a HashSet.  For URL based configuration,
        //this can leak memory
        if (beanFactory instanceof AbstractBeanFactory) {
            ((AbstractBeanFactory) beanFactory).getMergedBeanDefinition(bn);
        }
        super.configureBean(beanInstance);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Successfully performed injection,used beanName:{}", beanName);
        }
    } catch (NoSuchBeanDefinitionException ex) {
        // users often wonder why the settings in their configuration files seem
        // to have no effect - the most common cause is that they have been using
        // incorrect bean ids
        if (LOG.isDebugEnabled()) {
            LOG.debug("No matching bean {}", beanName);
        }
    }
}

From source file:com.amour.imagecrawler.ImagesManager.java

/**
 * Using Spring IoC to load the Images plug-ins
 * @param propertiesManager The Properties-Manager
 *///from  ww  w  .ja v a  2  s .  c o  m
public void loadPlugins(Properties propertiesManager) {

    imagePlugins = new ArrayList<>();
    String pulugins = propertiesManager.getProperty(Crawler.IMAGES_PLUGINS_TO_LOAD_KEY);

    Map pluginsMap = new HashMap<>();
    ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    for (String pluginKey : pulugins.split(",")) {

        if (!pluginsMap.containsKey(pluginKey)) {
            if (!context.containsBean(pluginKey)) {

                Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, "Plugin not exist");
                continue;
            }
            Object plugin = context.getBean(pluginKey);
            if (plugin instanceof ImagePlugin) {

                imagePlugins.add((ImagePlugin) plugin);
            }
            pluginsMap.put(pluginKey, pluginKey);
        }
    }
}

From source file:org.red5.server.plugin.oflaDemo.OflaDemoPlugin.java

@Override
public void doStart() throws Exception {
    super.doStart();

    //create a handler
    handler = new OflaDemoHandler();

    ApplicationContext commonCtx = (ApplicationContext) context.getBean("red5.common");

    if (context.containsBean("playlistSubscriberStream")) {
        //create app context
        oflaDemoContext = new FileSystemXmlApplicationContext(new String[] { "classpath:/oflaDemo.xml" }, true,
                context);//  www. j a  v  a  2 s .  co m
    } else if (commonCtx.containsBean("playlistSubscriberStream")) {
        //create app context
        oflaDemoContext = new FileSystemXmlApplicationContext(new String[] { "classpath:/oflaDemo.xml" }, true,
                commonCtx);
    } else {
        log.error("Playlist subscriber stream bean could not be located");
    }

    //set the context
    handler.setContext(oflaDemoContext);

    //get a ref to the "default" global scope
    GlobalScope global = (GlobalScope) server.getGlobal("default");

    //create a scope resolver
    ScopeResolver scopeResolver = new ScopeResolver();
    scopeResolver.setGlobalScope(global);

    //create a context - this takes the place of the previous web context
    Context ctx = new Context(oflaDemoContext, "oflaDemo");
    ctx.setClientRegistry(new ClientRegistry());
    ctx.setMappingStrategy(new MappingStrategy());
    ctx.setPersistanceStore(global.getStore());
    ctx.setScopeResolver(scopeResolver);
    ctx.setServiceInvoker(new ServiceInvoker());

    //create a scope for the admin
    Scope scope = new Scope.Builder((IScope) global, ScopeType.APPLICATION, "oflaDemo", false).build();
    scope.setContext(ctx);
    scope.setHandler(handler);

    //set the scope on the handler
    handler.setScope(scope);

    server.addMapping(hostName, "oflaDemo", "default");

    if (global.addChildScope(scope)) {
        log.info("oflaDemo scope was added to global (default) scope");

    } else {
        log.warn("oflaDemo scope was not added to global (default) scope");
    }
}

From source file:fr.itinerennes.bundler.cli.GtfsItinerennesBundler.java

private List<AbstractTask> verifySelectedTasksExists(final ApplicationContext ctx) {
    if (tasks.isEmpty()) {
        tasks.addAll(Arrays.asList(ctx.getBeanNamesForType(AbstractTask.class)));
    }//from  w  w w. jav a 2s  .co m
    final List<AbstractTask> selectedTasks = new ArrayList<AbstractTask>();
    final List<String> missingTasks = new ArrayList<String>();
    for (final String tName : tasks) {
        if (ctx.containsBean(tName)) {
            selectedTasks.add(ctx.getBean(tName, AbstractTask.class));
            LOGGER.info("Added task '{}' in execution queue", tName);
        } else {
            missingTasks.add(tName);
            LOGGER.error("Task '{}' doesn't exist", tName);
        }
    }
    if (!missingTasks.isEmpty()) {
        System.exit(1);
    }
    return selectedTasks;
}

From source file:org.jasig.springframework.web.portlet.context.PortletContextLoaderTests.java

@Test
public void testClassPathXmlApplicationContext() throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/springframework/web/context/WEB-INF/applicationContext.xml");
    assertTrue("Has father", context.containsBean("father"));
    assertTrue("Has rod", context.containsBean("rod"));
    assertFalse("Hasn't kerry", context.containsBean("kerry"));
    assertTrue("Doesn't have spouse", ((TestBean) context.getBean("rod")).getSpouse() == null);
    assertTrue("myinit not evaluated", "Roderick".equals(((TestBean) context.getBean("rod")).getName()));

    context = new ClassPathXmlApplicationContext(
            new String[] { "/org/springframework/web/context/WEB-INF/applicationContext.xml",
                    "/org/springframework/web/context/WEB-INF/context-addition.xml" });
    assertTrue("Has father", context.containsBean("father"));
    assertTrue("Has rod", context.containsBean("rod"));
    assertTrue("Has kerry", context.containsBean("kerry"));
}

From source file:net.kaleidos.mapping.i18n.UrlMappingsHolderFactoryBean.java

/**
 * Set the ApplicationContext that this object runs in.
 * Normally this call will be used to initialize the object.
 * <p>Invoked after population of normal bean properties but before an init callback such
 * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
 * or a custom init-method. Invoked after {@link org.springframework.context.ResourceLoaderAware#setResourceLoader},
 * {@link org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher} and
 * {@link org.springframework.context.MessageSourceAware}, if applicable.
 *
 * @param applicationContext the ApplicationContext object to be used by this object
 * @throws org.springframework.context.ApplicationContextException
 *          in case of context initialization errors
 * @throws org.springframework.beans.BeansException
 *          if thrown by application context methods
 * @see org.springframework.beans.factory.BeanInitializationException
 *///from w  ww . j a  v  a 2  s .c om
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    setGrailsApplication(applicationContext.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class));
    setServletContext(applicationContext instanceof WebApplicationContext
            ? ((WebApplicationContext) applicationContext).getServletContext()
            : null);
    setPluginManager(applicationContext.containsBean(GrailsPluginManager.BEAN_NAME)
            ? applicationContext.getBean(GrailsPluginManager.BEAN_NAME, GrailsPluginManager.class)
            : null);
}

From source file:org.ops4j.pax.wicket.spi.springdm.injection.spring.SpringBeanProxyTargetLocator.java

@Override
protected BeanReactor<ApplicationContext> createStrategy() {
    if (getBeanName().isEmpty()) {
        return new AbstractProxyTargetLocator.BeanReactor<ApplicationContext>() {
            public boolean containsBean(ApplicationContext applicationContext) {
                try {
                    applicationContext.getBean(beanType);
                } catch (NoSuchBeanDefinitionException e) {
                    return false;
                }//ww  w .  j  a v a 2  s .  co  m
                return true;
            }

            public Object createBean(ApplicationContext applicationContext) {
                return applicationContext.getBean(beanType);
            }
        };
    }
    if (overwrites == null || overwrites.size() == 0 || !overwrites.containsKey(getBeanName())) {
        return new AbstractProxyTargetLocator.BeanReactor<ApplicationContext>() {
            public boolean containsBean(ApplicationContext applicationContext) {
                return applicationContext.containsBean(getBeanName());
            }

            public Object createBean(ApplicationContext applicationContext) {
                return applicationContext.getBean(getBeanName(), beanType);
            }
        };
    }
    return new AbstractProxyTargetLocator.BeanReactor<ApplicationContext>() {
        public boolean containsBean(ApplicationContext applicationContext) {
            return applicationContext.containsBean(overwrites.get(getBeanName()));
        }

        public Object createBean(ApplicationContext applicationContext) {
            return applicationContext.getBean(overwrites.get(getBeanName()), beanType);
        }
    };
}