Java Code Examples for org.springframework.context.ApplicationContext#containsBean()

The following examples show how to use org.springframework.context.ApplicationContext#containsBean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScopeUtils.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns scope services (e.g. SharedObject, etc) for the scope. Method uses either bean name passes as a string or class object.
 *
 * @param scope
 *            The scope service belongs to
 * @param name
 *            Bean name
 * @param defaultClass
 *            Class of service
 * @return Service object
 */
protected static Object getScopeService(IScope scope, String name, Class<?> defaultClass) {
    if (scope != null) {
        final IContext context = scope.getContext();
        ApplicationContext appCtx = context.getApplicationContext();
        Object result;
        if (!appCtx.containsBean(name)) {
            if (defaultClass == null) {
                return null;
            }
            try {
                result = defaultClass.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                log.error("{}", e);
                return null;
            }
        } else {
            result = appCtx.getBean(name);
        }
        return result;
    }
    return null;
}
 
Example 2
Source File: BeanNameViewResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public View resolveViewName(String viewName, Locale locale) throws BeansException {
	ApplicationContext context = getApplicationContext();
	if (!context.containsBean(viewName)) {
		if (logger.isDebugEnabled()) {
			logger.debug("No matching bean found for view name '" + viewName + "'");
		}
		// Allow for ViewResolver chaining...
		return null;
	}
	if (!context.isTypeMatch(viewName, View.class)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found matching bean for view name '" + viewName +
					"' - to be ignored since it does not implement View");
		}
		// Since we're looking into the general ApplicationContext here,
		// let's accept this as a non-match and allow for chaining as well...
		return null;
	}
	return context.getBean(viewName, View.class);
}
 
Example 3
Source File: BeanNameViewResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public View resolveViewName(String viewName, Locale locale) throws BeansException {
	ApplicationContext context = getApplicationContext();
	if (!context.containsBean(viewName)) {
		if (logger.isDebugEnabled()) {
			logger.debug("No matching bean found for view name '" + viewName + "'");
		}
		// Allow for ViewResolver chaining...
		return null;
	}
	if (!context.isTypeMatch(viewName, View.class)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found matching bean for view name '" + viewName +
					"' - to be ignored since it does not implement View");
		}
		// Since we're looking into the general ApplicationContext here,
		// let's accept this as a non-match and allow for chaining as well...
		return null;
	}
	return context.getBean(viewName, View.class);
}
 
Example 4
Source File: SpringExtensionFactory.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
    for (ApplicationContext context : contexts) {
        if (context.containsBean(name)) {
            Object bean = context.getBean(name);
            if (type.isInstance(bean)) {
                return (T) bean;
            }
        }
    }
    return null;
}
 
Example 5
Source File: BusWiringBeanFactoryPostProcessor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Bus addDefaultBus(ApplicationContext ctx) {
    if (!ctx.containsBean(Bus.DEFAULT_BUS_ID)) {
        Bus b = getBusForName(Bus.DEFAULT_BUS_ID, ctx, true);
        if (ctx instanceof ConfigurableApplicationContext) {
            ConfigurableApplicationContext cctx = (ConfigurableApplicationContext)ctx;
            new BusWiringBeanFactoryPostProcessor(b).postProcessBeanFactory(cctx.getBeanFactory());
        }
    }
    return Bus.class.cast(ctx.getBean(Bus.DEFAULT_BUS_ID, Bus.class));
}
 
Example 6
Source File: SocketBeanConfigurator.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
	T endpoint = null;
	ApplicationContext appContext = Springs.getInstance().getAppContext();
	Component ann = AnnotationUtils.findAnnotation(endpointClass, Component.class);
	if (ann != null && appContext.containsBean(ann.value())) {
		endpoint = appContext.getBean(ann.value(), endpointClass);
		return endpoint;
	}
	
	Map<String, T> socketEndpointMap = Springs.getInstance().getBeansMap(endpointClass);
	if(LangUtils.isEmpty(socketEndpointMap)){
		endpoint = ReflectUtils.newInstance(endpointClass);
		SpringUtils.injectAndInitialize(appContext, ReflectUtils.newInstance(endpointClass));
		return endpoint;
	}
	if(socketEndpointMap.size()==1){
		endpoint = LangUtils.getFirst(socketEndpointMap);
	}else{
		String beanName = ClassUtils.getShortNameAsProperty(endpointClass);
		if (socketEndpointMap.containsKey(beanName)) {
			endpoint = socketEndpointMap.get(beanName);
			return endpoint;
		}
	}
	return endpoint;
}
 
Example 7
Source File: LogMdc.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static void setup(SecurityContext securityContext) {
    String userProp = AppContext.getProperty("cuba.logUserName");
    if (userProp == null || Boolean.valueOf(userProp)) {
        if (securityContext != null) {
            String user = securityContext.getUser();
            if (user == null) {
                UserSession session = securityContext.getSession();
                if (session != null)
                    user = session.getUser().getLogin();
                else if (securityContext.getSessionId() != null) {
                    ApplicationContext applicationContext = AppContext.getApplicationContext();
                    if (applicationContext.containsBean("cuba_UserSessions")) {
                        UserSessionFinder sessionFinder = (UserSessionFinder) applicationContext.getBean("cuba_UserSessions");
                        session = sessionFinder.get(securityContext.getSessionId());
                        if (session != null) {
                            user = session.getUser().getLogin();
                        }
                    }
                }
            }
            if (user != null) {
                MDC.put(USER, "/" + user);
            }
        } else {
            MDC.remove(USER);
        }
    }

    String applicationProp = AppContext.getProperty("cuba.logAppName");
    if (applicationProp == null || Boolean.valueOf(applicationProp)) {
        if (securityContext != null) {
            MDC.put(APPLICATION, "/" + AppContext.getProperty("cuba.webContextName"));
        } else {
            MDC.remove(APPLICATION);
        }
    }
}
 
Example 8
Source File: HibernateMappingContextConfiguration.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(applicationContext);
    String dsName = ConnectionSource.DEFAULT.equals(dataSourceName) ? "dataSource" : "dataSource_" + dataSourceName;
    Properties properties = getProperties();

    if(applicationContext.containsBean(dsName)) {
        properties.put(Environment.DATASOURCE, applicationContext.getBean(dsName));
    }
    properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContext.getName());
    properties.put(AvailableSettings.CLASSLOADERS, applicationContext.getClassLoader());
}
 
Example 9
Source File: SpringExtensionFactory.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
    for (ApplicationContext context : contexts) {
        if (context.containsBean(name)) {
            Object bean = context.getBean(name);
            if (type.isInstance(bean)) {
                return (T) bean;
            }
        }
    }
    return null;
}
 
Example 10
Source File: SpringExtensionFactory.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
    for (ApplicationContext context : contexts) {
        if (context.containsBean(name)) {
            Object bean = context.getBean(name);
            if (type.isInstance(bean)) {
                return (T) bean;
            }
        }
    }
    return null;
}
 
Example 11
Source File: NextServerApplication.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public Object getSpringBean(String beanName) {
	ApplicationContext applicationContext = WebApplicationContextUtils
			.getWebApplicationContext(getServletContext());
	if (!applicationContext.containsBean(beanName)) {
		return null;
	}

	return applicationContext.getBean(beanName);
}
 
Example 12
Source File: SpringExtensionFactory.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
    for (ApplicationContext context : contexts) {
        if (context.containsBean(name)) {
            Object bean = context.getBean(name);
            if (type.isInstance(bean)) {
                return (T) bean;
            }
        }
    }
    return null;
}
 
Example 13
Source File: KnowledgeServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	boolean hasBean=applicationContext.containsBean(KnowledgePackageService.BEAN_ID);
	if(hasBean){
		knowledgePackageService=(KnowledgePackageService)applicationContext.getBean(KnowledgePackageService.BEAN_ID);		
	}
}
 
Example 14
Source File: ActionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
* Loads this executor into the ApplicationContext, if it isn't already there
*/
public static void registerIfNeeded(ApplicationContext ctx)
{
    if (!ctx.containsBean(SleepActionExecuter.NAME))
    {
        // Create, and do dependencies
        SleepActionExecuter executor = new SleepActionExecuter();
        executor.setTrackStatus(true);
        executor.actionTrackingService = (ActionTrackingService) ctx.getBean("actionTrackingService");
        // Register
        ((ConfigurableApplicationContext) ctx).getBeanFactory().registerSingleton(SleepActionExecuter.NAME, executor);
    }
}
 
Example 15
Source File: RenditionServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Loads this executor into the ApplicationContext, if it
 *  isn't already there
 */
public static void registerIfNeeded(ApplicationContext ctx)
{
   if(!ctx.containsBean(ENGINE_NAME))
   {
      // Create, and do dependencies
      DummyHelloWorldRenditionEngine hw = new DummyHelloWorldRenditionEngine();
      hw.setRuntimeActionService(
            (RuntimeActionService)ctx.getBean("actionService")
      );
      hw.setNodeService(
            (NodeService)ctx.getBean("NodeService")
      );
      hw.setContentService(
            (ContentService)ctx.getBean("ContentService")
      );
      hw.setRenditionService(
            (RenditionService)ctx.getBean("RenditionService")
      );
      hw.setBehaviourFilter(
            (BehaviourFilter)ctx.getBean("policyBehaviourFilter")
      );
      hw.setRenditionLocationResolver(
            (RenditionLocationResolver)ctx.getBean("renditionLocationResolver")
      );
      
      // Register
       ((ConfigurableApplicationContext) ctx).getBeanFactory().registerSingleton(
            ENGINE_NAME, hw
      );
      hw.init();
   }
}
 
Example 16
Source File: ConfigurationPropertiesBinder.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
private Validator getConfigurationPropertiesValidator(
        ApplicationContext applicationContext, String validatorBeanName) {
    if (applicationContext.containsBean(validatorBeanName)) {
        return applicationContext.getBean(validatorBeanName, Validator.class);
    }
    return null;
}
 
Example 17
Source File: AbstractView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the {@link RequestDataValueProcessor} to use.
 * <p>The default implementation looks in the {@link #getApplicationContext()
 * Spring configuration} for a {@code RequestDataValueProcessor} bean with
 * the name {@link #REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME}.
 * @return the RequestDataValueProcessor, or null if there is none at the
 * application context.
 */
@Nullable
protected RequestDataValueProcessor getRequestDataValueProcessor() {
	ApplicationContext context = getApplicationContext();
	if (context != null && context.containsBean(REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
		return context.getBean(REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
	}
	return null;
}
 
Example 18
Source File: ConfigurerImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public synchronized void configureBean(String bn, Object beanInstance, boolean checkWildcards) {

        if (null == appContexts) {
            return;
        }

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

        if (checkWildcards) {
            configureWithWildCard(bn, beanInstance);
        }

        final String beanName = bn;
        setBeanWiringInfoResolver(new BeanWiringInfoResolver() {
            public BeanWiringInfo resolveWiringInfo(Object instance) {
                if (!beanName.isEmpty()) {
                    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.isLoggable(Level.FINE)) {
                LOG.fine("Successfully performed injection.");
            }
        } 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.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "NO_MATCHING_BEAN_MSG", beanName);
            }
        }
    }
 
Example 19
Source File: CoreSpringFactory.java    From olat with Apache License 2.0 2 votes vote down vote up
/**
 * @param beanName
 *            The bean name to check for
 * @return true if such a bean does exist, false otherwhise. But if such a bean definition exists it will get created! Use the containsSingleton to check for lazy
 *         init beans whether they are instantiated or not.
 */
public static boolean containsBean(String beanName) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    return context.containsBean(beanName);
}
 
Example 20
Source File: CoreSpringFactory.java    From olat with Apache License 2.0 2 votes vote down vote up
/**
 * @param beanName
 *            The bean name to check for
 * @return true if such a bean does exist, false otherwhise. But if such a bean definition exists it will get created! Use the containsSingleton to check for lazy
 *         init beans whether they are instantiated or not.
 */
public static boolean containsBean(String beanName) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    return context.containsBean(beanName);
}