@SuppressWarnings("unchecked") @Test public void defaultServletConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(DefaultConfigurationServlet.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition servletRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationServlet.class.getName()); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat(((Map<String, String>) propertyValues.get("initParameters"))) .isEmpty(); assertThat((Integer) propertyValues.get("loadOnStartup")).isEqualTo(-1); assertThat(propertyValues.get("name")) .isEqualTo(DefaultConfigurationServlet.class.getName()); assertThat((String[]) propertyValues.get("urlMappings")).isEmpty(); assertThat(propertyValues.get("servlet")).isEqualTo(scanned); }
@SuppressWarnings("unchecked") @Test public void defaultFilterConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(DefaultConfigurationFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationFilter.class.getName()); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat((EnumSet<DispatcherType>) propertyValues.get("dispatcherTypes")) .containsExactly(DispatcherType.REQUEST); assertThat(((Map<String, String>) propertyValues.get("initParameters"))) .isEmpty(); assertThat((String[]) propertyValues.get("servletNames")).isEmpty(); assertThat((String[]) propertyValues.get("urlPatterns")).isEmpty(); assertThat(propertyValues.get("name")) .isEqualTo(DefaultConfigurationFilter.class.getName()); assertThat(propertyValues.get("filter")).isEqualTo(scanned); }
@SuppressWarnings("unchecked") @Test public void defaultServletConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(DefaultConfigurationServlet.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition servletRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationServlet.class.getName()); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); assertThat(propertyValues.get("asyncSupported"), is((Object) false)); assertThat(((Map<String, String>) propertyValues.get("initParameters")).size(), is(0)); assertThat((Integer) propertyValues.get("loadOnStartup"), is(-1)); assertThat(propertyValues.get("name"), is((Object) DefaultConfigurationServlet.class.getName())); assertThat((String[]) propertyValues.get("urlMappings"), is(arrayWithSize(0))); assertThat(propertyValues.get("servlet"), is(equalTo((Object) scanned))); }
@SuppressWarnings("unchecked") @Test public void defaultFilterConfiguration() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(DefaultConfigurationFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationFilter.class.getName()); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported"), is((Object) false)); assertThat((EnumSet<DispatcherType>) propertyValues.get("dispatcherTypes"), is(EnumSet.of(DispatcherType.REQUEST))); assertThat(((Map<String, String>) propertyValues.get("initParameters")).size(), is(0)); assertThat((String[]) propertyValues.get("servletNames"), is(arrayWithSize(0))); assertThat((String[]) propertyValues.get("urlPatterns"), is(arrayWithSize(0))); assertThat(propertyValues.get("name"), is((Object) DefaultConfigurationFilter.class.getName())); assertThat(propertyValues.get("filter"), is(equalTo((Object) scanned))); }
@Override protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages); Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinition> candidates = findCandidateComponents(basePackage); if (candidates.isEmpty()) { logger.warn("No MyBatis mapper was found in 'ffff' package. Please check your configuration."); } else { for (BeanDefinition beanDefinition : candidates) { if(beanDefinition instanceof ScannedGenericBeanDefinition){ ScannedGenericBeanDefinition sgBeanDefinition = (ScannedGenericBeanDefinition)beanDefinition; Map<String, Object> metaMap = sgBeanDefinition.getMetadata().getAnnotationAttributes(annotationMappingClass.getName()); String parent = RestDataUtils.typeAnnotationAttributesResolver(metaMap); String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, super.getRegistry()); registerRestInfo(beanName, beanDefinition, sgBeanDefinition, parent, RestAnotationType.MAPPING); registerRestInfo(beanName, beanDefinition, sgBeanDefinition, parent, RestAnotationType.VALIDATOR); } } } RestHandlerMethodMapping.registerGenericRestful(applicationContext.getBean(GENERIC_RESTFUL_SERVICE)); return beanDefinitionHolders; }
void handle(ScannedGenericBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { Map<String, Object> attributes = beanDefinition.getMetadata() .getAnnotationAttributes(this.annotationType.getName()); if (attributes != null) { doHandle(attributes, beanDefinition, registry); } }
private void scanPackage(ClassPathScanningCandidateComponentProvider componentProvider, String packageToScan) { for (BeanDefinition candidate : componentProvider.findCandidateComponents(packageToScan)) { if (candidate instanceof ScannedGenericBeanDefinition) { for (ServletComponentHandler handler : HANDLERS) { handler.handle(((ScannedGenericBeanDefinition) candidate), (BeanDefinitionRegistry) this.applicationContext); } } } }
private void scanPackage( ClassPathScanningCandidateComponentProvider componentProvider, String packageToScan) { for (BeanDefinition candidate : componentProvider .findCandidateComponents(packageToScan)) { if (candidate instanceof ScannedGenericBeanDefinition) { for (ServletComponentHandler handler : HANDLERS) { handler.handle(((ScannedGenericBeanDefinition) candidate), (BeanDefinitionRegistry) this.applicationContext); } } } }
@Test public void listener() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(TestListener.class.getName())); this.handler.handle(scanned, this.registry); this.registry.getBeanDefinition(TestListener.class.getName()); }
@Test public void servletWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(CustomNameServlet.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition servletRegistrationBean = this.registry .getBeanDefinition("custom"); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); assertThat(propertyValues.get("name")).isEqualTo("custom"); }
BeanDefinition getBeanDefinition(Class<?> filterClass) throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(filterClass.getName())); this.handler.handle(scanned, this.registry); return this.registry.getBeanDefinition(filterClass.getName()); }
@Test public void filterWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(CustomNameFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry.getBeanDefinition("custom"); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("name")).isEqualTo("custom"); }
@Test public void servletWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(CustomNameServlet.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition servletRegistrationBean = this.registry .getBeanDefinition("custom"); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); assertThat(propertyValues.get("name"), is((Object) "custom")); }
@Test public void filterWithCustomName() throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(CustomNameFilter.class.getName())); this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry.getBeanDefinition("custom"); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("name"), is((Object) "custom")); }
/** * @param args * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException { ITestAnnotation iTestAnnotation = new ITestAnnotation() { @Override public void test() { System.out.println("test test"); } }; ClassPathScanningCandidateComponentProviderExtend provider = new ClassPathScanningCandidateComponentProviderExtend(false); provider.addIncludeFilter(new AnnotationTypeFilter(TestAnnotation.class)); String basePackage = "com/doctor"; Set<ScannedGenericBeanDefinition> components = provider.findCandidateComponents(basePackage); for (ScannedGenericBeanDefinition component : components) { System.out.printf("Component: %s\n", component.getBeanClassName()); System.out.println(component.getMetadata().getAnnotationTypes()); Class<?> classT = Class.forName(component.getBeanClassName()); Set<MethodMetadata> annotatedMethods = component.getMetadata().getAnnotatedMethods("com.doctor.practice01.TestAnnotation"); for (MethodMetadata methodMetadata : annotatedMethods) { System.out.println(methodMetadata.getMethodName()); System.out.println(methodMetadata.getDeclaringClassName()); System.out.println(methodMetadata.getReturnTypeName()); System.out.println(methodMetadata.getAnnotationAttributes("com.doctor.practice01.TestAnnotation")); MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetMethod(methodMetadata.getMethodName()); methodInvoker.setTargetObject(iTestAnnotation); methodInvoker.prepare(); methodInvoker.invoke(); } } }
private void scanAppRepository(AbstractApplicationContext context, Component component) { String appRepository = component.getManifestAttribute(APP_REPOSITORY); if (StringUtils.isEmpty(appRepository)) { return; } int count; if (context instanceof AnnotationConfigRegistry) { int before = context.getBeanDefinitionCount(); ((AnnotationConfigRegistry) context).scan(StringUtils.split(appRepository, CONFIG_LOCATION_DELIMITERS)); count = context.getBeanDefinitionCount() - before; } else { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) context); scanner.setEnvironment(context.getEnvironment()); scanner.setResourceLoader(context); scanner.setIncludeAnnotationConfig(false); count = scanner.scan(StringUtils.split(appRepository, CONFIG_LOCATION_DELIMITERS)); } if (count > 0 && logger.isDebugEnabled()) { logger.debug("Scanned {} beans in {}", count, component.getDisplayName()); String[] names = context.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = ((GenericApplicationContext) context).getBeanDefinition(name); if (definition instanceof ScannedGenericBeanDefinition) { ScannedGenericBeanDefinition sgbd = (ScannedGenericBeanDefinition) definition; Class<?> beanClass; try { beanClass = sgbd.resolveBeanClass(context.getClassLoader()); } catch (ClassNotFoundException e) { continue; } if (beanClass != null) { logger.debug("\t{}", beanClass.getName()); } } } } }
private void registerRestInfo(String beanName, BeanDefinition beanDefinition, ScannedGenericBeanDefinition sgBeanDefinition, String parent, RestAnotationType type) { String annotationClassName = null; if(RestAnotationType.MAPPING == type){ annotationClassName = annotationMappingClass.getName(); }else if(RestAnotationType.VALIDATOR == type){ annotationClassName = annotationValidatorClass.getName(); } Set<MethodMetadata> methodMetadata = sgBeanDefinition.getMetadata().getAnnotatedMethods(annotationClassName); Iterator<MethodMetadata> iterator = methodMetadata.iterator(); while(iterator.hasNext()){ RestAnotationMetadata info = new RestAnotationMetadata(); info.setParent(parent); MethodMetadata mmd = iterator.next(); Map<String, Object> valueMap = mmd.getAnnotationAttributes(annotationClassName); if(null != valueMap){ info = RestDataUtils.methodAnnotationAttributesResolver(valueMap, info); info.setType(type); } RestMethodMappingInfo restMethodMappingInfo = RestDataUtils.buildRestMethodMappingInfo(beanDefinition.getBeanClassName(), mmd.getMethodName()); info.setMethodMappingInfo(restMethodMappingInfo); if(RestAnotationType.MAPPING == type){ RestHandlerMethodMapping.registerRestMethodMapping(info); }else if(RestAnotationType.VALIDATOR == type){ RestHandlerMethodMapping.registerRestValidatorMapping(info); } RestHandlerMethod restHandlerMethod = RestDataUtils.buildRestHandlerMethod(beanName, mmd.getMethodName(), info.getTable()); if(null != restMethodMappingInfo && null != restHandlerMethod){ RestHandlerMethodMapping.registerHandlerMethod(restMethodMappingInfo, restHandlerMethod); } } }
@Override protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(); for (String basePackage : basePackages) { Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { String originalBeanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); String beanName = this.exporterBeanNameGenerator.generateBeanName(candidate, this.registry); if(beanName == null || beanName.isEmpty()) { beanName = candidate.getBeanClassName(); // 确保beanName有值 } // beanName必须以/开头 if(!beanName.startsWith("/")) { beanName = "/" + beanName; } beanName = "/" + Constants.HESSOA_URL_PREFIX + beanName; ScannedGenericBeanDefinition bd = (ScannedGenericBeanDefinition) candidate; String[] interfaces = bd.getMetadata().getInterfaceNames(); if (interfaces == null || interfaces.length == 0) { throw new RuntimeException("@HessianService bean must implement at least one interface"); } Class<?> interf = null; Class<?> annoInterf = (Class<?>) getAnnotationValue(bd.getMetadata(), "value"); if(annoInterf != null) { if(annoInterf.isInterface()) { interf = annoInterf; } else { throw new RuntimeException("@HessianService value must be interface class"); } } else { throw new RuntimeException("@HessianService must have value (interface)"); } /** * 下面这一段,实际上等价于xml配置 */ BeanDefinitionBuilder hessianBeanDef = BeanDefinitionBuilder.genericBeanDefinition(SOAHessianServiceExporter.class); hessianBeanDef.addPropertyReference("service", originalBeanName); hessianBeanDef.addPropertyValue("beanName", beanName); hessianBeanDef.addPropertyValue("serviceInterface", interf.getName()); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder( hessianBeanDef.getBeanDefinition(), beanName); beanDefinitions.add(definitionHolder); registerBeanDefinition(definitionHolder, this.registry); } } // 打印扫描信息,可用于debug if (beanDefinitions.isEmpty()) { System.out.println("no service scaned"); } else { for (BeanDefinitionHolder holder : beanDefinitions) { System.out.println("scanned service:" + holder.getBeanName()); } } return beanDefinitions; }