public ThirdPayService route(PayChannel channel, PayType payType) throws Exception { if (thirdClassList == null) throw new Exception(ErrorMsgConstant.CHANNEL_NOT_SUPPORT); for (Class<?> clz : thirdClassList) { ChannelValue comment = clz.getAnnotation(ChannelValue.class); if (comment == null) continue; if (comment.channel() != channel) continue; if (!ArrayUtils.contains(comment.payType(), payType)) continue; Service service = clz.getAnnotation(Service.class); if (service == null) continue; return (ThirdPayService) SpringContextHelper.getBean(service.value()); } throw new Exception(ErrorMsgConstant.CHANNEL_NOT_SUPPORT); }
public ThirdBankVerifyService route(BankRequest request) throws Exception { if (request == null || request.getInfo().getChannel() == null) { throw new Exception("当前暂不支持的第三方支付渠道"); } if (thirdClassList == null) throw new Exception("当前暂不支持的第三方支付渠道"); for (Class<?> clz : thirdClassList) { ChannelValue comment = clz.getAnnotation(ChannelValue.class); if (comment == null) continue; if (comment.channel() != request.getInfo().getChannel()) continue; Service service = clz.getAnnotation(Service.class); if (service == null) continue; return (ThirdBankVerifyService) SpringContextHelper.getBean(service.value()); } throw new Exception("当前暂不支持的第三方支付渠道"); }
private void parseCacheDuration(ApplicationContext applicationContext) { final Map<String, Long> cacheExpires = new HashMap<>(); String[] beanNames = applicationContext.getBeanNamesForType(Object.class); for (String beanName : beanNames) { final Class clazz = applicationContext.getType(beanName); Service service = findAnnotation(clazz, Service.class); if (null == service) { continue; } addCacheExpires(clazz, cacheExpires); } logger.debug("初始化redisCacheManager, 配置有过期时间的key, 内容如下:" + cacheExpires); //设置有效期 super.setExpires(cacheExpires); }
@PostConstruct public void init() { List<Class<?>> classList = ClassUtil.getClasses(ArcticleService.class.getPackage().getName()); for (Class<?> aClass : classList) { if (aClass.isAnnotationPresent(Service.class)) { for (Method method : aClass.getDeclaredMethods()) { if (method.isAnnotationPresent(ValidateGroup.class)) { String key = method.toString(); LOGGER.info("init validators of method {}", key); validateConcurrentMap.put(key, getFiledValidators(key, method)); } } } } }
private String getBeanName(Class<?> clazz) { Component component = clazz.getAnnotation(Component.class); if (component != null) return component.value(); Repository repository = clazz.getAnnotation(Repository.class); if (repository != null) return repository.value(); Service service = clazz.getAnnotation(Service.class); if (service != null) return service.value(); Controller controller = clazz.getAnnotation(Controller.class); if (controller != null) return controller.value(); return null; }
@Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesWithMetaAnnotationWithDefaultAttributes() throws Exception { Class<?> startClass = MetaConfigWithDefaultAttributesTestCase.class; Class<ContextConfiguration> annotationType = ContextConfiguration.class; UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class); assertNotNull(descriptor); assertEquals(startClass, descriptor.getRootDeclaringClass()); assertEquals(annotationType, descriptor.getAnnotationType()); assertArrayEquals(new Class[] {}, ((ContextConfiguration) descriptor.getAnnotation()).value()); assertArrayEquals(new Class[] { MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class }, descriptor.getAnnotationAttributes().getClassArray("classes")); assertNotNull(descriptor.getComposedAnnotation()); assertEquals(MetaConfig.class, descriptor.getComposedAnnotationType()); }
@Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesWithMetaAnnotationWithOverriddenAttributes() throws Exception { Class<?> startClass = MetaConfigWithOverriddenAttributesTestCase.class; Class<ContextConfiguration> annotationType = ContextConfiguration.class; UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class); assertNotNull(descriptor); assertEquals(startClass, descriptor.getRootDeclaringClass()); assertEquals(annotationType, descriptor.getAnnotationType()); assertArrayEquals(new Class[] {}, ((ContextConfiguration) descriptor.getAnnotation()).value()); assertArrayEquals(new Class[] { MetaAnnotationUtilsTests.class }, descriptor.getAnnotationAttributes().getClassArray("classes")); assertNotNull(descriptor.getComposedAnnotation()); assertEquals(MetaConfig.class, descriptor.getComposedAnnotationType()); }
public void resetAndReconfigure(boolean debug) { SingularContextSetup.reset(); ApplicationContextMock applicationContext = new ApplicationContextMock(); ServiceRegistryLocator.setup(new SpringServiceRegistry()); new ApplicationContextProvider().setApplicationContext(applicationContext); registerBeanFactories(applicationContext); registerAnnotated(applicationContext, Named.class); registerAnnotated(applicationContext, Service.class); registerAnnotated(applicationContext, Component.class); registerAnnotated(applicationContext, Repository.class); registerMockitoTestClassMocksAndSpies(applicationContext); getLogger().info("Contexto configurado com os beans: "); if (debug) { applicationContext.listAllBeans().forEach( b -> getLogger().info(b) ); } }
@Override public List<MaraAnnotationHandler> getHandlers() throws ToolException { List<MaraAnnotationHandler> handlers = new ArrayList<>(); Reflections reflections = initReflections(getBasePackagesToScanForComponents()); Set<Class<?>> handlerClasses = reflections.getTypesAnnotatedWith(Service.class); for (Class<?> handlerClass : handlerClasses) { if (MaraAnnotationHandler.class.isAssignableFrom(handlerClass)) { try { MaraAnnotationHandler handler = (MaraAnnotationHandler) handlerClass.newInstance(); handlers.add(handler); } catch (InstantiationException | IllegalAccessException e) { throw new ToolException(e); } } } return handlers; }
@Before public void setup() throws ToolException { annotationUtil = MaraAnnotationUtil.INSTANCE; // Initialize our annotations handlers Configuration conf = new Configuration(); this.job = mock(Job.class); when(job.getConfiguration()).thenReturn(conf); AnnotatedTool tool = mock(AnnotatedTool.class); AnnotatedToolContext context = mock(AnnotatedToolContext.class); when(tool.getContext()).thenReturn(context); try { Reflections reflections = new Reflections("com.conversantmedia.mapreduce.tool.annotation"); Set<Class<?>> handlerClasses = reflections.getTypesAnnotatedWith(Service.class); for (Class<?> handlerClass : handlerClasses) { if (MaraAnnotationHandler.class.isAssignableFrom(handlerClass)) { MaraAnnotationHandler handler = (MaraAnnotationHandler) handlerClass.newInstance(); annotationUtil.registerAnnotationHandler(handler, tool); } } } catch (InstantiationException | IllegalAccessException e) { throw new ToolException(e); } }
private String getBeanName(final Class<?> clazz) { final Component componentAnno = clazz.getAnnotation(Component.class); if(componentAnno != null && !componentAnno.value().isEmpty()) { return componentAnno.value(); } final Service serviceAnno = clazz.getAnnotation(Service.class); if(serviceAnno != null && !serviceAnno.value().isEmpty()) { return serviceAnno.value(); } final Repository repositoryAnno = clazz.getAnnotation(Repository.class); if(repositoryAnno != null && !repositoryAnno.value().isEmpty()) { return repositoryAnno.value(); } final Controller controllerAnno = clazz.getAnnotation(Controller.class); if(controllerAnno != null && !controllerAnno.value().isEmpty()) { return controllerAnno.value(); } // ステレオタイプのアノテーションでBean名の指定がない場合は、クラス名の先頭を小文字にした名称とする。 return uncapitalize(clazz.getSimpleName()); }
private Annotation getSpringClassAnnotation(Class clazz) { Annotation classAnnotation = AnnotationUtils.findAnnotation(clazz, Component.class); if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Controller.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, RestController.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Service.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Repository.class); } return classAnnotation; }
@Nullable @Override public <T> AnnotatedComponent<T> process(Scope scope, Class<T> clazz) { Controller controller = clazz.getAnnotation(Controller.class); if (controller != null) { return new AnnotatedComponent(clazz, controller.value(), ComponentType.CONTROLLER); } Service service = clazz.getAnnotation(Service.class); if (service != null) { return new AnnotatedComponent(clazz, service.value(), ComponentType.CONTROLLER); } return null; }
public DwrClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { super(registry, false); addExcludeFilter(new AnnotationTypeFilter(Component.class)); addExcludeFilter(new AnnotationTypeFilter(Service.class)); addExcludeFilter(new AnnotationTypeFilter(Repository.class)); addExcludeFilter(new AnnotationTypeFilter(Controller.class)); setScopedProxyMode(ScopedProxyMode.INTERFACES); }
@Test public void testWithComponentAnnotationOnly() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AnnotationTypeFilter(Component.class)); provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class)); provider.addExcludeFilter(new AnnotationTypeFilter(Service.class)); provider.addExcludeFilter(new AnnotationTypeFilter(Controller.class)); Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); assertEquals(2, candidates.size()); assertTrue(containsBeanClass(candidates, NamedComponent.class)); assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); assertFalse(containsBeanClass(candidates, FooServiceImpl.class)); assertFalse(containsBeanClass(candidates, StubFooDao.class)); assertFalse(containsBeanClass(candidates, NamedStubDao.class)); }
@Test public void isProxy() throws Exception { TransactionalTestBean bean = getTestBean(); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); Map<String, Object> services = this.context.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); }
@Test public void transactionProxyIsCreated() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(EnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); Map<?,?> services = ctx.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); ctx.close(); }
@Test public void transactionProxyIsCreatedWithEnableOnSuperclass() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(InheritedEnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); Map<?,?> services = ctx.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); ctx.close(); }
@SuppressWarnings("unchecked") private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Class<?> startClass, Class<?> rootDeclaringClass, Class<?> declaringClass, String name, Class<? extends Annotation> composedAnnotationType) { Class<Component> annotationType = Component.class; UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class, annotationType, Order.class, Transactional.class); assertNotNull("UntypedAnnotationDescriptor should not be null", descriptor); assertEquals("rootDeclaringClass", rootDeclaringClass, descriptor.getRootDeclaringClass()); assertEquals("declaringClass", declaringClass, descriptor.getDeclaringClass()); assertEquals("annotationType", annotationType, descriptor.getAnnotationType()); assertEquals("component name", name, ((Component) descriptor.getAnnotation()).value()); assertNotNull("composedAnnotation should not be null", descriptor.getComposedAnnotation()); assertEquals("composedAnnotationType", composedAnnotationType, descriptor.getComposedAnnotationType()); }
/** * @since 4.0.3 */ @Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesOnAnnotatedClassWithMissingTargetMetaAnnotation() { // InheritedAnnotationClass is NOT annotated or meta-annotated with @Component, // @Service, or @Order, but it is annotated with @Transactional. UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(InheritedAnnotationClass.class, Service.class, Component.class, Order.class); assertNull("Should not find @Component on InheritedAnnotationClass", descriptor); }
/** * @since 4.0.3 */ @Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(MetaCycleAnnotatedClass.class, Service.class, Component.class, Order.class); assertNull("Should not find @Component on MetaCycleAnnotatedClass", descriptor); }
@ConditionalOnProperty(name = "javamelody.enableSpringServiceMonitoring", havingValue = "true") @Bean public MonitoringSpringAdvisor springServiceMonitoringAdvisor() { final MonitoringSpringAdvisor interceptor = new MonitoringSpringAdvisor(); interceptor.setPointcut(new AnnotationMatchingPointcut(Service.class)); return interceptor; }
/** * The method provides the functionality to retrieve all the service facades and initialize them * @see ServiceFacade * @see com.castlemock.core.basis.model.Service */ protected void initializeServiceFacade(){ final Map<String, Object> components = applicationContext.getBeansWithAnnotation(Service.class); for(Map.Entry<String, Object> entry : components.entrySet()){ final Object value = entry.getValue(); if(value instanceof ServiceFacade){ final ServiceFacade serviceFacade = (ServiceFacade) value; serviceFacade.initiate(); } } }
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { Class<?> clazz = bean.getClass(); if (clazz.isAnnotationPresent(Service.class)) { Method[] methodArr = clazz.getDeclaredMethods(); for (Method method : methodArr) { if (method.isAnnotationPresent(CmdTrace.class)) { CmdTrace cmdTrace = method.getAnnotation(CmdTrace.class); Class<? extends SubCommand> cmdClazz = cmdTrace.cmdClazz(); String methodName = clazz.getSimpleName() + "." + method.getName(); if (method2cmd.get(methodName) == null) { method2cmd.put(methodName, cmdClazz); } else { throw new IllegalStateException(methodName + " = {" + method2cmd.get(methodName).getName() + "," + cmdClazz.getName() + "}"); } if (cmd2method.get(cmdClazz) == null) { cmd2method.put(cmdClazz, methodName); } else { throw new IllegalStateException(cmdClazz + " = {" + cmd2method.get(cmdClazz) + "," + methodName + "}"); } } } } return bean; }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { log.info("Configuring remote services"); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; ApplicationContext coreContext = context.getParent(); 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) { 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"); } } }
public static String getServiceId(Annotation[] annotations) { String serviceId = ""; if (annotations == null) { return serviceId; } for (Annotation anno : annotations) { if (anno instanceof Service) { serviceId = ((Service)anno).value(); } } return serviceId; }
private String getTargetType(MethodInvocation methodInvocation) { Class<?> targetType = methodInvocation.getThis().getClass(); if (hasAnnotation(targetType, Controller.class)) { return "Controller"; } else if (hasAnnotation(targetType, Service.class)) { return "Service"; } else if (hasAnnotation(targetType, Repository.class)) { return "Repository"; } else { return "Trace"; } }
@Override public void delete(ObjectId id) { Dashboard dashboard = dashboardRepository.findOne(id); componentRepository.delete(dashboard.getApplication().getComponents()); // Remove this Dashboard's services and service dependencies serviceRepository.delete(serviceRepository.findByDashboardId(id)); for (com.capitalone.dashboard.model.Service service : serviceRepository.findByDependedBy(id)) { service.getDependedBy().remove(id); serviceRepository.save(service); } dashboardRepository.delete(dashboard); }
/** * 获取Service impl的Spring bean名称,首先根据@Service注解来判断,如果没有则为类的间单名 * * @param thriftServiceImplClass * @return */ private String getServiceImplBeanName(Class<?> thriftServiceImplClass) { if (thriftServiceImplClass.isAnnotationPresent(Service.class)) { Service serviceAnnotation = (Service) thriftServiceImplClass.getAnnotation(Service.class); String value = serviceAnnotation.value(); if (StringUtils.isEmpty(value)) { return StringUtils.uncapitalize(thriftServiceImplClass.getSimpleName()); } else { return value; } } else { return StringUtils.uncapitalize(thriftServiceImplClass.getSimpleName()); } }
/** * 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); } }
@Test public void transactionProxyIsCreated() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(EnableTxConfig.class, TxManagerConfig.class); ctx.refresh(); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertThat("testBean is not a proxy", AopUtils.isAopProxy(bean), is(true)); Map<?,?> services = ctx.getBeansWithAnnotation(Service.class); assertThat("Stereotype annotation not visible", services.containsKey("testBean"), is(true)); }
@Test public void transactionProxyIsCreatedWithEnableOnSuperclass() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(InheritedEnableTxConfig.class, TxManagerConfig.class); ctx.refresh(); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertThat("testBean is not a proxy", AopUtils.isAopProxy(bean), is(true)); Map<?,?> services = ctx.getBeansWithAnnotation(Service.class); assertThat("Stereotype annotation not visible", services.containsKey("testBean"), is(true)); }
private Annotation getSpringClassAnnotation(Class clazz){ Annotation classAnnotation = AnnotationUtils.findAnnotation(clazz, Component.class); if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Controller.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Service.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Repository.class); } return classAnnotation; }
@Test public void testMe() { assertEquals(4, myService3.onePlusThree()); System.out.println(this.getClass().getSimpleName() + " -> " + applicationContext.getId()); assertEquals(3, applicationContext.getBeansWithAnnotation(Service.class).size()); }
@Test public void testMe() { assertEquals(2, myService1.onePlusOne()); System.out.println(this.getClass().getSimpleName() + " -> " + applicationContext.getId()); assertEquals(3, applicationContext.getBeansWithAnnotation(Service.class).size()); }
@Test public void testMe() { assertEquals(2, myService1.onePlusOne()); System.out.println(this.getClass().getSimpleName() + " -> " + applicationContext.getId()); assertEquals(1, applicationContext.getBeansWithAnnotation(Service.class).size()); }
@Test public void testMe() { assertEquals(3, myService2.onePlusTwo()); System.out.println(this.getClass().getSimpleName() + " -> " + applicationContext.getId()); assertEquals(3, applicationContext.getBeansWithAnnotation(Service.class).size()); }
@Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesForClassWithMetaAnnotatedInterface() { assertNull(findAnnotationDescriptorForTypes(ClassWithMetaAnnotatedInterface.class, Service.class, Component.class, Order.class, Transactional.class)); }