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

The following examples show how to use org.springframework.context.ApplicationContext#getBeansWithAnnotation() . 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: JobSpringExecutor.java    From datax-web with 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 2
Source File: XxlJobSpringExecutor.java    From zuihou-admin-boot with Apache License 2.0 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 (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 3
Source File: XxlJobExecutor.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
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 4
Source File: XxlMqSpringClientFactory.java    From xxl-mq with GNU General Public License v3.0 6 votes vote down vote up
@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 5
Source File: UrlBeanNameUiMapping.java    From jdal with 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 6
Source File: XxlRpcSpringProviderFactory.java    From datax-web with 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 7
Source File: SpringBootstrap.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 8
Source File: SpringUtils.java    From onetwo with 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 9
Source File: SpringTimeHandler.java    From springtime with 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 10
Source File: ApiBootstrap.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 11
Source File: RpcServer.java    From buddha with 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 12
Source File: RpcProviderProcessor.java    From hasting with 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 13
Source File: LionServer.java    From lionrpc with 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 14
Source File: HttpServerHandler.java    From netty-http-server with Apache License 2.0 5 votes vote down vote up
@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 15
Source File: RpcServer.java    From springboot-learn with 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 16
Source File: CoreSpringFactory.java    From olat with 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 17
Source File: RPCServer.java    From rpc4j with 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 18
Source File: AbstractBuilder.java    From urule with 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 File: HippoServerInit.java    From hippo with 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 File: RemoteServicesBeanCreator.java    From cuba with 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);
            }
        }
    }
}