Kotlin使用spring-boot搭建restful api

主题

 使用kotlin 语言,加上spring-boot框架,使用gradle构建的restful风格的api应用,顺便熟悉kotlin语法特性

特性

  • restful 风格api举例
  • Token 身份验证,使用过滤器
  • 方法级别权限控制api接口
  • 处理异常,自定义返回结果
  • servlet异步响应
  • model数据处理

代码

http://gitter.com/blueswu/spring-boot-restful   

处理异常自定返回


@RestController
class GreetingController {

    @ExceptionHandler
    @ResponseBody
    fun handleServiceException(req:HttpServletRequest , response:HttpServletResponse , e:Exception ):ErrorResponse  
    {
       var status = HttpStatus.OK.value() 
       status = when(e){
        is AccessDeniedException -> HttpStatus.FORBIDDEN.value()
	else -> status
       }

       if(status != 200){
          val error = ErrorResponse(status,e.getLocalizedMessage())
         response.setStatus(status)
         return error
      }
       else throw e
    }
}

servlet异步响应

  1. 入口处注册EnableAsync
@SpringBootApplication
@EnableAsync
open class Application{
@Bean
@Qualifier(value = "taskExecutor")
open fun  taskExecutor(): Executor  {
        val executor:ThreadPoolTaskExecutor = ThreadPoolTaskExecutor()
        executor.setCorePoolSize(2)
        executor.setMaxPoolSize(2)
        executor.setQueueCapacity(500)
        executor.setThreadNamePrefix("GithubLookup-")
        executor.initialize()
        return executor
 }
}
  1. service处理类方法注册Async
@Service
class LookService {
   @Async("taskExecutor")
   fun  findUsers():CompletableFuture<User> {
      val results:User =User(0,"all users") 
      Thread.sleep(5000L)
       return CompletableFuture.completedFuture(results)
   }
}

方法级别权限控制

  1. 安全设置EnableGlobalMethodSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
open class WebSecurityConfig : WebSecurityConfigurerAdapter() {
}
  1. Controller注册PreAuthorize
@RestController
class GreetingController {
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")  
        fun getUsers( ) {
    }
}

转载于:https://my.oschina.net/jackywyz/blog/1477323

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值