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

The following examples show how to use org.springframework.context.ApplicationContext#getBeansWithAnnotation() . These examples are extracted from open source projects. 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 Project: datax-web   File: XxlRpcSpringProviderFactory.java    License: MIT License 6 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(XxlRpcService.class);
    if (serviceBeanMap!=null && serviceBeanMap.size()>0) {
        for (Object serviceBean : serviceBeanMap.values()) {
            // valid
            if (serviceBean.getClass().getInterfaces().length ==0) {
                throw new XxlRpcException("xxl-rpc, service(XxlRpcService) must inherit interface.");
            }
            // add service
            XxlRpcService xxlRpcService = serviceBean.getClass().getAnnotation(XxlRpcService.class);

            String iface = serviceBean.getClass().getInterfaces()[0].getName();
            String version = xxlRpcService.version();

            super.addService(iface, version, serviceBean);
        }
    }

    // TODO,addServices by api + prop

}
 
Example 2
Source Project: datax-web   File: JobSpringExecutor.java    License: MIT License 6 votes vote down vote up
private void initJobHandlerRepository(ApplicationContext applicationContext) {
    if (applicationContext == null) {
        return;
    }

    // init job handler action
    Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(JobHandler.class);

    if (CollectionUtil.isNotEmpty(serviceBeanMap)) {
        for (Object serviceBean : serviceBeanMap.values()) {
            if (serviceBean instanceof IJobHandler) {
                String name = serviceBean.getClass().getAnnotation(JobHandler.class).value();
                IJobHandler handler = (IJobHandler) serviceBean;
                if (loadJobHandler(name) != null) {
                    throw new RuntimeException("datax-web jobhandler[" + name + "] naming conflicts.");
                }
                registJobHandler(name, handler);
            }
        }
    }
}
 
Example 3
private void initJobHandlerRepository(ApplicationContext applicationContext) {
    if (applicationContext == null) {
        return;
    }

    // init job handler action
    Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(JobHandler.class);

    if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
        for (Object serviceBean : serviceBeanMap.values()) {
            if (serviceBean instanceof IJobHandler) {
                String name = serviceBean.getClass().getAnnotation(JobHandler.class).value();
                IJobHandler handler = (IJobHandler) serviceBean;
                if (loadJobHandler(name) != null) {
                    throw new RuntimeException("xxl-job jobhandler naming conflicts. name = " + name);
                }
                registJobHandler(name, handler);
            }
        }
    }
}
 
Example 4
private static void initJobHandlerRepository(ApplicationContext applicationContext){
    if (applicationContext == null) {
        return;
    }

    // init job handler action
    Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(JobHandler.class);

    if (serviceBeanMap!=null && serviceBeanMap.size()>0) {
        for (Object serviceBean : serviceBeanMap.values()) {
            if (serviceBean instanceof IJobHandler){
                String name = serviceBean.getClass().getAnnotation(JobHandler.class).value();
                IJobHandler handler = (IJobHandler) serviceBean;
                if (loadJobHandler(name) != null) {
                    throw new RuntimeException("xxl-job jobhandler naming conflicts.");
                }
                registJobHandler(name, handler);
            }
        }
    }
}
 
Example 5
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    // load consumer from spring
    List<IMqConsumer> consumerList = new ArrayList<>();

    Map<String, Object> serviceMap = applicationContext.getBeansWithAnnotation(MqConsumer.class);
    if (serviceMap!=null && serviceMap.size()>0) {
        for (Object serviceBean : serviceMap.values()) {
            if (serviceBean instanceof IMqConsumer) {
                consumerList.add((IMqConsumer) serviceBean);
            }
        }
    }

    // init
    xxlMqClientFactory = new XxlMqClientFactory();

    xxlMqClientFactory.setAdminAddress(adminAddress);
    xxlMqClientFactory.setAccessToken(accessToken);
    xxlMqClientFactory.setConsumerList(consumerList);

    xxlMqClientFactory.init();
}
 
Example 6
Source Project: jdal   File: UrlBeanNameUiMapping.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Init th url map parsing {@link UiMapping} annotations
 * @param ctx ApplicationContext
 */
@Autowired
public void init(ApplicationContext ctx) {
	Map<String, Object> uis = ctx.getBeansWithAnnotation(UiMapping.class);
	
	for (String name : uis.keySet()) {
		Object ui = uis.get(name);
		if (ui instanceof UI) {
			UiMapping ann = AnnotationUtils.findAnnotation(ui.getClass(), UiMapping.class);
			if (ann != null) {
				if (log.isDebugEnabled())
					log.debug("Mapping UI [" + ui.getClass().getName() + "] to request path [" + ann.value() + "]");
				this.urlMap.put(ann.value(), name);
			}
		}
	}
}
 
Example 7
Source Project: rpc4j   File: RPCServer.java    License: MIT License 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(RPCService.class);
    if (MapUtils.isNotEmpty(serviceBeanMap)) {
        for (Object serviceBean : serviceBeanMap.values()) {
            String interfaceName = serviceBean.getClass().getAnnotation(RPCService.class).value().getName();
            handlerMap.put(interfaceName, serviceBean);
        }
    }
}
 
Example 8
Source Project: olat   File: CoreSpringFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Prototype-method : Get service which is annotated with '@Service'.
 * 
 * @param <T>
 * @param serviceType
 * @return Service of requested type, must not be casted.
 * @throws RuntimeException
 *             when more than one service of the same type is registered. RuntimeException when servie is not annotated with '@Service'.
 * 
 *             *******not yet in use********
 */
private static <T> T getService(Class<T> serviceType) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    Map<String, T> m = context.getBeansOfType(serviceType);
    if (m.size() > 1) {
        throw new OLATRuntimeException("found more than one service for: " + serviceType + ". Calling this method should only find one service-bean!", null);
    }
    T service = context.getBean(serviceType);
    Map<String, ?> services = context.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
    if (services.containsValue(service)) {
        return service;
    } else {
        throw new OLATRuntimeException("Try to get Service which is not annotated with '@Service', services must have '@Service'", null);
    }
}
 
Example 9
Source Project: springboot-learn   File: RpcServer.java    License: MIT License 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class);
    if (MapUtils.isNotEmpty(serviceBeanMap)) {
        for (Object serviceBean : serviceBeanMap.values()) {
            String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).value().getName();
            logger.info("Loading service: {}", interfaceName);
            handlerMap.put(interfaceName, serviceBean);
        }
    }
}
 
Example 10
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
    Map<String, Object> handlers =  applicationContext.getBeansWithAnnotation(NettyHttpHandler.class);
    for (Map.Entry<String, Object> entry : handlers.entrySet()) {
        Object handler = entry.getValue();
        Path path = Path.make(handler.getClass().getAnnotation(NettyHttpHandler.class));
        if (functionHandlerMap.containsKey(path)){
            LOGGER.error("IFunctionHandler has duplicated :" + path.toString(),new IllegalPathDuplicatedException());
            System.exit(0);
        }
        functionHandlerMap.put(path, (IFunctionHandler) handler);
    }
}
 
Example 11
public void init(){
   ApplicationContext applicationContext =  ApplicationContextHelper.getApplicationContext();
    Map<String, Object> extensionBeans = applicationContext.getBeansWithAnnotation(Extension.class);
    extensionBeans.values().forEach(
            extension -> extensionRegister.doRegistration((ExtensionPointI) extension)
    );

    Map<String, Object> eventHandlerBeans = applicationContext.getBeansWithAnnotation(EventHandler.class);
    eventHandlerBeans.values().forEach(
            eventHandler -> eventRegister.doRegistration((EventHandlerI) eventHandler)
    );
}
 
Example 12
Source Project: lionrpc   File: LionServer.java    License: Apache License 2.0 5 votes vote down vote up
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    Map<String,Object> lionServiceMap = applicationContext.getBeansWithAnnotation(LionService.class);
    if(lionServiceMap != null){
        for (Object serviceBean : lionServiceMap.values()) {
            String interfaceName = serviceBean.getClass().getAnnotation(LionService.class).value().getName();
            serverHandlerMap.put(interfaceName, serviceBean);
        }
    }
}
 
Example 13
Source Project: hasting   File: RpcProviderProcessor.java    License: MIT License 5 votes vote down vote up
private void registerRpcs(ApplicationContext apc){
	Map<String, Object> map = apc.getBeansWithAnnotation(RpcProviderService.class);
	Collection<Object> values = map.values();
	for(Object obj:values){
		RpcProviderService providerService = obj.getClass().getAnnotation(RpcProviderService.class);
		Class<?>[] ifs = obj.getClass().getInterfaces();
		for(Class<?> iface:ifs){
			RpcProviderService service = providerService;
			if(service==null){
				service = iface.getAnnotation(RpcProviderService.class);
			}
			if(service!=null){
				String bean = service.rpcServer();
				if(bean==null){
					bean = DEFAULT_RPC_BEAN;
				}
				AbstractRpcServer server = serverMap.get(bean);
				if(server==null){
					throw new BeanCreationException("can't find rpcServer of name:"+bean);
				}
				server.register(iface, obj,service.version());
				logger.info("register rpc bean:"+iface+" bean:"+bean);
			}
		}
	}
	logger.info("register rpc service success");
}
 
Example 14
Source Project: buddha   File: RpcServer.java    License: MIT License 5 votes vote down vote up
public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
    Map<String, Object> serviceMap = applicationContext.getBeansWithAnnotation(RpcService.class);
    if (MapUtils.isNotEmpty(serviceMap)) {
        for (Object bean : serviceMap.values()) {
            String interfaceName = bean.getClass().getAnnotation(RpcService.class).value().getName();
            handlerMap.put(interfaceName, bean);
        }
    }
}
 
Example 15
@Override
protected void onBootstrap(ApplicationEvent event)
{
    logger.info("Bootstapping the API");
    ContextRefreshedEvent refreshEvent = (ContextRefreshedEvent)event;
    ApplicationContext ac = refreshEvent.getApplicationContext();
    Map<String, Object> entityResourceBeans = ac.getBeansWithAnnotation(EntityResource.class);
    Map<String, Object> relationResourceBeans = ac.getBeansWithAnnotation(RelationshipResource.class);
    apiDictionary.setDictionary(ResourceDictionaryBuilder.build(entityResourceBeans.values(), relationResourceBeans.values()));
}
 
Example 16
Source Project: springtime   File: SpringTimeHandler.java    License: Apache License 2.0 5 votes vote down vote up
public SpringTimeHandler(ApplicationContext applicationContext) {
	ServiceBeanFactory serviceBeanFactory = new ServiceBeanFactory();
	//TODO: 检查名称重复的方法
	Map<String, Object> beans = applicationContext.getBeansWithAnnotation(SpringTimeService.class);
	for (Entry<String, Object> entry : beans.entrySet()) {
		serviceBeanFactory.add(RPC_PREFIX, entry.getKey(), entry.getValue());
	}

	dispatcher = new ServiceDispatcher(serviceBeanFactory);
}
 
Example 17
Source Project: onetwo   File: SpringUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T extends Annotation> List<WithAnnotationBeanData<T>> getBeansWithAnnotation(ApplicationContext applicationContext, Class<T> annotationType){
	Map<String, Object> beans = applicationContext.getBeansWithAnnotation(annotationType);
	return beans.entrySet().stream().map(e->{
		T annotation = AnnotationUtils.findAnnotation(e.getValue().getClass(), annotationType);
		WithAnnotationBeanData<T> data = new WithAnnotationBeanData<T>(annotation, e.getKey(), e.getValue());
		return data;
	})
	.collect(Collectors.toList());
}
 
Example 18
Source Project: urule   File: AbstractBuilder.java    License: Apache License 2.0 4 votes vote down vote up
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	resourceBuilders=applicationContext.getBeansOfType(ResourceBuilder.class).values();
	providers=applicationContext.getBeansOfType(ResourceProvider.class).values();
	this.applicationContext=applicationContext;
	applicationContext.getBeansWithAnnotation(SuppressWarnings.class);
}
 
Example 19
Source Project: hippo   File: HippoServerInit.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext ctx) {
    //init fixed theadcount
    HippoServerThreadPool.FIXED.setThreadCount(threadCount);

    Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(HippoServiceImpl.class);

    if (MapUtils.isEmpty(serviceBeanMap)) {
        throw new HippoServiceException(
                "该项目依赖了hippo-server,在接口实现类请使用[@HippoServiceImpl]来声明");
    }

    Map<String, Object> implObjectMap = HippoServiceCache.INSTANCE.getImplObjectMap();
    Map<String, FastClass> implClassMap = HippoServiceCache.INSTANCE.getImplClassMap();
    Map<String, Class<?>> interfaceMap = HippoServiceCache.INSTANCE.getInterfaceMap();
    for (Object serviceBean : serviceBeanMap.values()) {
        String simpleName = null;
        Class<?> clazz = AopUtils.isAopProxy(serviceBean) ? AopUtils.getTargetClass(serviceBean) : serviceBean.getClass();
        Class<?>[] interfaces = clazz.getInterfaces();
        int index = 0;
        for (Class<?> class1 : interfaces) {
            //兼容@HippoService方式
            HippoService annotation = class1.getAnnotation(HippoService.class);
            if (annotation == null && CommonUtils.isJavaClass(class1)) {
                continue;
            }
            if (index == 1) {
                throw new HippoServiceException(
                        serviceBean.getClass().getName() + "已经实现了[" + simpleName + "]接口,hippoServiceImpl不允许实现2个接口。");
            }
            simpleName = class1.getSimpleName();
            index++;
            // simpleName 提供apiProcess使用
            // 全限定名提供给rpcProcess使用
            String name = class1.getName();
            //提供给apigate访问的方式是接口名+方法名,所以会导致apigate访问过来找到2个实现类导致异常
            if (implObjectMap.containsKey(simpleName)) {
                throw new HippoServiceException(
                        "接口[" + simpleName + "]已存在。[" + name + "],hippo不支持不同包名但接口名相同,请重命名当前接口名");
            }
            implObjectMap.put(name, serviceBean);
            interfaceMap.put(simpleName, class1);
            implClassMap.put(name, FastClass.create(clazz));
            if (annotation != null) {
                registryNames.add(annotation.serviceName());
            } else {
                metaMap.put(name, serviceName);
            }
        }
    }
}
 
Example 20
Source Project: cuba   File: RemoteServicesBeanCreator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void postProcessBeanFactory(@Nonnull ConfigurableListableBeanFactory beanFactory) throws BeansException {
    log.info("Configuring remote services");

    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    ApplicationContext coreContext = context.getParent();
    if (coreContext == null) {
        throw new RuntimeException("Parent Spring context is null");
    }

    Map<String,Object> services = coreContext.getBeansWithAnnotation(Service.class);
    for (Map.Entry<String, Object> entry : services.entrySet()) {
        String serviceName = entry.getKey();
        Object service = entry.getValue();

        List<Class> serviceInterfaces = new ArrayList<>();
        List<Class<?>> interfaces = ClassUtils.getAllInterfaces(service.getClass());
        for (Class intf : interfaces) {
            if (intf.getName().endsWith("Service"))
                serviceInterfaces.add(intf);
        }
        String intfName = null;
        if (serviceInterfaces.size() == 0) {
            log.error("Bean " + serviceName + " has @Service annotation but no interfaces named '*Service'. Ignoring it.");
        } else if (serviceInterfaces.size() > 1) {
            intfName = findLowestSubclassName(serviceInterfaces);
            if (intfName == null)
                log.error("Bean " + serviceName + " has @Service annotation and more than one interface named '*Service', " +
                        "but these interfaces are not from the same hierarchy. Ignoring it.");
        } else {
            intfName = serviceInterfaces.get(0).getName();
        }
        if (intfName != null) {
            if (ServiceExportHelper.exposeServices()) {
                BeanDefinition definition = new RootBeanDefinition(HttpServiceExporter.class);
                MutablePropertyValues propertyValues = definition.getPropertyValues();
                propertyValues.add("service", service);
                propertyValues.add("serviceInterface", intfName);
                registry.registerBeanDefinition("/" + serviceName, definition);
                log.debug("Bean " + serviceName + " configured for export via HTTP");
            } else {
                ServiceExportHelper.registerLocal("/" + serviceName, service);
            }
        }
    }
}