org.springframework.web.bind.annotation.RestController源码实例Demo

类org.springframework.web.bind.annotation.RestController源码实例Demo

下面列出了怎么用org.springframework.web.bind.annotation.RestController的API类实例代码及写法,或者点击链接到github查看源代码。

private Predicate<RequestHandler> getControllerPredicate() {
    groupName = groupList.get(groupIndex);
    List<String> apiTags = groupMap.get(groupName);
    Predicate<RequestHandler> methodPredicate = (input) -> {
        Api api = null;
        Optional<Api> apiOptional = input.findControllerAnnotation(Api.class);
        if (apiOptional.isPresent()) {
            api = apiOptional.get();
        }
        List<String> tags = Arrays.asList(api.tags());
        if (api != null && apiTags.containsAll(tags)) {
            return true;
        }
        return false;
    };
    groupIndex++;
    return Predicates.and(RequestHandlerSelectors.withClassAnnotation(RestController.class), methodPredicate);
}
 
源代码2 项目: Jpom   文件: WebAopLog.java
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
    if (aopLogInterface != null) {
        aopLogInterface.before(joinPoint);
    }
    // 接收到请求,记录请求内容
    IS_LOG.set(ExtConfigBean.getInstance().isConsoleLogReqResponse());
    Signature signature = joinPoint.getSignature();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        ResponseBody responseBody = methodSignature.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody == null) {
            RestController restController = joinPoint.getTarget().getClass().getAnnotation(RestController.class);
            if (restController == null) {
                IS_LOG.set(false);
            }
        }
    }
}
 
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) {
    setRequestContext(request);
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    //判断当前请求是否为接口
    boolean hasResponseBody = method.isAnnotationPresent(ResponseBody.class);
    boolean hasRestController = handlerMethod.getBeanType().isAnnotationPresent(RestController.class);
    RequestContext requestContext = WebContextFacade.getRequestContext();
    requestContext.setApiRequest(hasResponseBody || hasRestController);
    WebContextFacade.setRequestContext(requestContext);
    return true;
}
 
源代码4 项目: java-tutorial   文件: SwaggerConfig.java
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .pathMapping("/")
            .select()
            .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .paths(PathSelectors.any())
            .build().apiInfo(new ApiInfoBuilder()
                    .title("OAuth2.0 API ")
                    .description("api docs")
                    .version("1.0")
                    .contact(new Contact("jarvis", "github.com", "[email protected]"))
                    .license("The Apache License")
                    .licenseUrl("https://www.github.com")
                    .build());
}
 
源代码5 项目: seed   文件: LogConfiguration.java
@Override
public Pointcut getPointcut() {
    return new StaticMethodMatcherPointcut(){
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
            //若类上面注解了DisableLog,则不打印日志(仅此类,不包括该类中被调用的类)
            if(targetClass.isAnnotationPresent(DisableLog.class)){
                return false;
            }
            //若方法上面注解了DisableLog,则不打印日志
            if(method.isAnnotationPresent(DisableLog.class)){
                return false;
            }
            //若类上面注解了EnableLog,则打印日志
            if(targetClass.isAnnotationPresent(EnableLog.class)){
                return true;
            }
            //若方法上面注解了EnableLog,则打印日志
            if(method.isAnnotationPresent(EnableLog.class)){
                return true;
            }
            //默认的:打印标注了RestController的类、以及ResponseBody的方法,的日志
            return targetClass.isAnnotationPresent(RestController.class) || method.isAnnotationPresent(ResponseBody.class);
        }
    };
}
 
源代码6 项目: WebIDE-Backend   文件: SwaggerConfig.java
@Bean
public Docket petApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(withClassAnnotation(RestController.class))
            .build()
            .pathMapping("/")
            .enableUrlTemplating(true)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(
                    HttpServletRequest.class,
                    HttpServletResponse.class,
                    HttpSession.class,
                    Pageable.class,
                    Errors.class
            );
}
 
源代码7 项目: molgenis   文件: ExceptionHandlerFacadeImpl.java
private ExceptionResponseType getExceptionResponseType(HandlerMethod handlerMethod) {
  ExceptionResponseType exceptionResponseType;

  Class<?> beanType = handlerMethod.getBeanType();
  if (ApiController.class.isAssignableFrom(beanType)) {
    exceptionResponseType = PROBLEM;
  } else if (handlerMethod.hasMethodAnnotation(ResponseStatus.class)
      || handlerMethod.hasMethodAnnotation(ResponseBody.class)
      || beanType.isAnnotationPresent(ResponseBody.class)
      || beanType.isAnnotationPresent(RestController.class)) {
    exceptionResponseType = ERROR_MESSAGES;
  } else {
    exceptionResponseType = MODEL_AND_VIEW;
  }

  return exceptionResponseType;
}
 
@Override
public boolean canProcess(Class<?> cls) {
  if (cls.getAnnotation(RestController.class) != null) {
    return true;
  }
  return false;
}
 
private static boolean canProcess(Class<?> loadClass) {

    if (loadClass == null) {
      return false;
    }
    RestSchema restSchema = loadClass.getAnnotation(RestSchema.class);
    if (restSchema != null) {
      return true;
    }

    RestController controller = loadClass.getAnnotation(RestController.class);
    if (controller != null) {
      return true;
    }

    RpcSchema rpcSchema = loadClass.getAnnotation(RpcSchema.class);
    if (rpcSchema != null) {
      return true;
    }

    RequestMapping requestMapping = loadClass.getAnnotation(RequestMapping.class);
    if (requestMapping != null) {
      return true;
    }

    Path pathAnnotation = loadClass.getAnnotation(Path.class);
    if (pathAnnotation != null) {
      return true;
    }
    return false;
  }
 
@Test
public void testPrivateCanProcess() throws Exception {
  DefaultContractsGenerator defaultContractsGenerator = new DefaultContractsGenerator();
  Method method = defaultContractsGenerator.getClass().getDeclaredMethod("canProcess", Class.class);
  method.setAccessible(true);

  assertThat(method.invoke(defaultContractsGenerator, new Object[] {null}), is(false));

  Class mockClass;
  ContractTestUtil contractTestUtil = new ContractTestUtil();

  CtClass ctClass = contractTestUtil.createCtClass("TestCanProcess");
  assertThat(method.invoke("TestCanProcess", ctClass.toClass()), is(false));

  mockClass = contractTestUtil.putAnnotationToClass("TestRestSchema", RestSchema.class);
  assertThat(method.invoke("TestRestSchema", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestRestController", RestController.class);
  assertThat(method.invoke("TestRestController", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestRpcSchema", RpcSchema.class);
  assertThat(method.invoke("TestRpcSchema", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestRequestMapping", RequestMapping.class);
  assertThat(method.invoke("TestRequestMapping", mockClass), is(true));

  mockClass = contractTestUtil.putAnnotationToClass("TestPath", Path.class);
  assertThat(method.invoke("TestPath", mockClass), is(true));
}
 
源代码11 项目: spring-openapi   文件: OpenAPIGenerator.java
private Map<String, PathItem> createPathExtensions() {
ClassPathScanningCandidateComponentProvider scanner = createClassPathScanningCandidateComponentProvider();
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));

      List<Class<?>> controllerClasses = new ArrayList<>();
      List<String> packagesWithoutRegex = removeRegexFormatFromPackages(controllerBasePackages);
      for (String controllerPackage : packagesWithoutRegex) {
          logger.debug("Scanning controller package=[{}]", controllerPackage);
          for (BeanDefinition beanDefinition : scanner.findCandidateComponents(controllerPackage)) {
              logger.debug("Scanning controller class=[{}]", beanDefinition.getBeanClassName());
              controllerClasses.add(getClass(beanDefinition));
          }
      }
      return operationsTransformer.transformOperations(controllerClasses);
  }
 
源代码12 项目: spring-openapi   文件: OpenAPIV2Generator.java
private Map<String, Path> createPaths(OpenApiV2GeneratorConfig config) {
	ClassPathScanningCandidateComponentProvider scanner = createClassPathScanningCandidateComponentProvider();
	scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));

	List<Class<?>> controllerClasses = new ArrayList<>();
	List<String> packagesWithoutRegex = removeRegexFormatFromPackages(controllerBasePackages);
	for (String controllerPackage : packagesWithoutRegex) {
		logger.debug("Scanning controller package=[{}]", controllerPackage);
		for (BeanDefinition beanDefinition : scanner.findCandidateComponents(controllerPackage)) {
			logger.debug("Scanning controller class=[{}]", beanDefinition.getBeanClassName());
			controllerClasses.add(getClass(beanDefinition));
		}
	}
	return operationsTransformer.transformOperations(controllerClasses, config);
}
 
@Test
public void pathPrefix() throws Exception {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			info.getPatternsCondition().getPatterns());
}
 
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton("/api/user/{id}"), info.getPatternsCondition().getPatterns());
}
 
源代码15 项目: springdoc-openapi   文件: OpenAPIBuilder.java
/**
 * Build.
 */
public void build() {
	Optional<OpenAPIDefinition> apiDef = getOpenAPIDefinition();

	if (openAPI == null) {
		this.calculatedOpenAPI = new OpenAPI();
		this.calculatedOpenAPI.setComponents(new Components());
		this.calculatedOpenAPI.setPaths(new Paths());
	}
	else
		this.calculatedOpenAPI = openAPI;

	if (apiDef.isPresent()) {
		buildOpenAPIWithOpenAPIDefinition(calculatedOpenAPI, apiDef.get());
	}
	// Set default info
	else if (calculatedOpenAPI.getInfo() == null) {
		Info infos = new Info().title(DEFAULT_TITLE).version(DEFAULT_VERSION);
		calculatedOpenAPI.setInfo(infos);
	}
	// Set default mappings
	this.mappingsMap.putAll(context.getBeansWithAnnotation(RestController.class));
	this.mappingsMap.putAll(context.getBeansWithAnnotation(RequestMapping.class));
	this.mappingsMap.putAll(context.getBeansWithAnnotation(Controller.class));

	// add security schemes
	this.calculateSecuritySchemes(calculatedOpenAPI.getComponents());
	openApiBuilderCustomisers.ifPresent(customisers -> customisers.forEach(customiser -> customiser.customise(this)));
}
 
源代码16 项目: Jpom   文件: BaseJpomInterceptor.java
static boolean isPage(HandlerMethod handlerMethod) {
    ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
    if (responseBody == null) {
        RestController restController = handlerMethod.getBeanType().getAnnotation(RestController.class);
        return restController == null;
    }
    return false;
}
 
源代码17 项目: archunit-examples   文件: SpringCodingRulesTest.java
@Test
public void springSingletonComponentsShouldOnlyHaveFinalFields() {
  ArchRule rule = ArchRuleDefinition.classes()
    .that().areAnnotatedWith(Service.class)
    .or().areAnnotatedWith(Component.class)
    .and().areNotAnnotatedWith(ConfigurationProperties.class)
    .or().areAnnotatedWith(Controller.class)
    .or().areAnnotatedWith(RestController.class)
    .or().areAnnotatedWith(Repository.class)
    .should().haveOnlyFinalFields();
  rule.check(classes);
}
 
源代码18 项目: sbp   文件: PluginRequestMappingHandlerMapping.java
public Set<Object> getControllerBeans(SpringBootPlugin springBootPlugin) {
    LinkedHashSet<Object> beans = new LinkedHashSet<>();
    ApplicationContext applicationContext = springBootPlugin.getApplicationContext();
    //noinspection unchecked
    Set<String> sharedBeanNames = (Set<String>) applicationContext.getBean(
            SpringBootstrap.BEAN_IMPORTED_BEAN_NAMES);
    beans.addAll(applicationContext.getBeansWithAnnotation(Controller.class)
            .entrySet().stream().filter(beanEntry -> !sharedBeanNames.contains(beanEntry.getKey()))
            .map(Map.Entry::getValue).collect(Collectors.toList()));
    beans.addAll(applicationContext.getBeansWithAnnotation(RestController.class)
            .entrySet().stream().filter(beanEntry -> !sharedBeanNames.contains(beanEntry.getKey()))
            .map(Map.Entry::getValue).collect(Collectors.toList()));
    return beans;
}
 
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			info.getPatternsCondition().getPatterns());
}
 
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton("/api/user/{id}"), info.getPatternsCondition().getPatterns());
}
 
源代码21 项目: FATE-Serving   文件: GlobalResponseController.java
@Override
public boolean supports(MethodParameter methodParameter, Class converterType) {

    Boolean isRest = AnnotationUtils.isAnnotationDeclaredLocally(
            RestController.class, methodParameter.getContainingClass());
    ResponseBody responseBody = AnnotationUtils.findAnnotation(
            methodParameter.getMethod(), ResponseBody.class);

    if (responseBody != null || isRest) {
        return true;
    } else {
        return false;
    }

}
 
源代码22 项目: soul   文件: SpringMvcClientBeanPostProcessor.java
@Override
public Object postProcessBeforeInitialization(@NonNull final Object bean, @NonNull final String beanName) throws BeansException {
    if (soulSpringMvcConfig.isFull()) {
        return bean;
    }
    Controller controller = AnnotationUtils.findAnnotation(bean.getClass(), Controller.class);
    RestController restController = AnnotationUtils.findAnnotation(bean.getClass(), RestController.class);
    RequestMapping requestMapping = AnnotationUtils.findAnnotation(bean.getClass(), RequestMapping.class);
    if (controller != null || restController != null || requestMapping != null) {
        String contextPath = soulSpringMvcConfig.getContextPath();
        SoulSpringMvcClient clazzAnnotation = AnnotationUtils.findAnnotation(bean.getClass(), SoulSpringMvcClient.class);
        String prePath = "";
        if (Objects.nonNull(clazzAnnotation)) {
            if (clazzAnnotation.path().indexOf("*") > 1) {
                post(buildJsonParams(clazzAnnotation, contextPath, prePath));
                return bean;
            }
            prePath = clazzAnnotation.path();
        }
        final Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(bean.getClass());
        for (Method method : methods) {
            SoulSpringMvcClient soulSpringMvcClient = AnnotationUtils.findAnnotation(method, SoulSpringMvcClient.class);
            if (Objects.nonNull(soulSpringMvcClient)) {
                post(buildJsonParams(soulSpringMvcClient, contextPath, prePath));
            }
        }
    }
    return bean;
}
 
源代码23 项目: ci-droid   文件: SwaggerConfiguration.java
@Bean
public Docket productApi() {
    Docket docket = new Docket(DocumentationType.SWAGGER_2)
            .select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .paths(PathSelectors.any())
            .build();
    return docket;
}
 
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
private void registerInclude() {
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
    //根据扫描包获取所有的类
    List<String> scanPackages = secretProperties.getScanPackages();
    if (!CollectionUtils.isEmpty(scanPackages)) {
        isScanAllController = false;
        for (String scanPackage : scanPackages) {
            Set<BeanDefinition> beanDefinitions = secretScanner.findCandidateComponents(scanPackage);
            for (BeanDefinition beanDefinition : beanDefinitions) {
                includeClassList.add(beanDefinition.getBeanClassName());
            }
        }
    }
}
 
private void registerExclude() {
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
    secretScanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
    //根据扫描包获取所有的类
    List<String> scanPackages = secretProperties.getExcludePackages();
    if (!CollectionUtils.isEmpty(scanPackages)) {
        for (String scanPackage : scanPackages) {
            Set<BeanDefinition> beanDefinitions = secretScanner.findCandidateComponents(scanPackage);
            for (BeanDefinition beanDefinition : beanDefinitions) {
                excludeClassList.add(beanDefinition.getBeanClassName());
            }
        }
    }
}
 
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class clazz = bean.getClass();
    if(clazz.isAnnotationPresent(RestController.class) || clazz.isAnnotationPresent(Controller.class)) {
        Method[] methods = clazz.getDeclaredMethods();
         for (Method method : methods) {
            int modifiers = method.getModifiers();
            if(Modifier.isPublic(modifiers) && method.isAnnotationPresent(DynamicRateLimiter.class)) {
                if(!redisLimiterProperties.isEnableDynamicalConf()) {
                    throw new RuntimeException("Must set spring.redis-limiter.enable-dynamical-conf = true, then you can use DynamicRateLimiter annotation.");
                }
                DynamicRateLimiter dynamicRateLimiter = method.getAnnotation(DynamicRateLimiter.class);
                int permits = dynamicRateLimiter.permits();
                TimeUnit timeUnit = dynamicRateLimiter.timeUnit();
                String path = dynamicRateLimiter.path();
                String baseExp = dynamicRateLimiter.base();
                LimiterConfig config = new LimiterConfig();
                config.setApplicationName(applicationName);
                config.setBaseExp(baseExp);
                config.setPath(path);
                config.setPermits(permits);
                config.setTimeUnit(timeUnit.name());
                config.setControllerName(clazz.getSimpleName());
                config.setMethodName(method.getName());
                String key = clazz.getSimpleName()+":"+method.getName();
                if(configMap.containsKey(key)) {
                    throw new RuntimeException(String.format("Controller %s method %s has conflict.", clazz.getSimpleName(), method.getName()));
                }
                configMap.put(key, config);
            }
        }
    }
    return bean;
}
 
源代码30 项目: BlogManagePlatform   文件: DefaultEndPointPlugin.java
private boolean isRestEndPoint(OperationContext context) {
	if (context.findControllerAnnotation(RestController.class).isPresent()) {
		return true;
	}
	if (context.findAnnotation(ResponseBody.class).isPresent()) {
		return true;
	}
	return false;
}
 
点击广告?(赏赐笔者)