Javalin 旨在为 Kotlin 和 Java 提供一个易用的轻量级 REST API 库。这个 REST API 易于使用,API 也非常的流畅。
Javalin 主要有以下的特点:
-
易用:不用提前学习任何概念就可以开始使用
-
一致的 API:所有的处理程序和映射器在 Context (ctx) 中都是无效的。
-
Kotlin 和 Java 拥有几乎完全相同的 API
-
是框架也是库:无需扩展任何功能
-
拥有完全可定制的嵌入式服务器 (Jetty)
-
JSON 对象映射
-
通过 AccessManager 接口简单的按端点验证
-
简单的静态文件处理
-
生命周期事件
-
CookieStore,一种简单的用来序列化的方法和存储在 cookie 中的对象。
-
模板渲染
-
Markdown 渲染
下面是用 Kotlin 实现的 “Hello World” API 的例子。
import io.javalin.Javalin;public class HelloWorld {public static void main(String[] args) {var app = Javalin.create(/*config*/).get("/", ctx -> ctx.result("Hello World")).start(7070);}
}
Request Handler 每个请求处理,或者匹配某些路径处理:
app.before(ctx -> {// runs before all requests
});
app.before("/path/*", ctx -> {// runs before request to /path/*
});
请求处理:
app.get("/output", ctx -> {// some codectx.json(object);
});app.post("/input", ctx -> {// some codectx.status(201);
});
Javalin官网文档地址
下面基于Javalin和springboot、Mybatis-Flex(Mybatis-Flex官网文档)实现一个简单的项目:
项目结构:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.2</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.kexuexiong</groupId><artifactId>shushan_server</artifactId><version>1.0-SNAPSHOT</version><properties><java.version>17</java.version><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>com.mybatis-flex</groupId><artifactId>mybatis-flex-spring-boot-starter</artifactId><version>1.5.3</version></dependency><dependency><groupId>com.mybatis-flex</groupId><artifactId>mybatis-flex-processor</artifactId><version>1.5.3</version><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version><scope>runtime</scope></dependency><dependency><groupId>io.javalin</groupId><artifactId>javalin</artifactId><version>5.6.1</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter-test</artifactId><version>3.0.2</version><scope>test</scope></dependency><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>4.0.3</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency><dependency><groupId>com.mybatis-flex</groupId><artifactId>mybatis-flex-codegen</artifactId><version>1.5.3</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>2.0.7</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
application.yml
spring:datasource:url: jdbc:mysql://数据库ip:3306/shushanusername: rootpassword: 密码mybatis-flex:mapper-locations:- classpath*:/mappers/*.xml
Application.java
package com.kexuexiong;import io.javalin.Javalin;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;import java.util.logging.Logger;@SpringBootApplication
@MapperScan("com.kexuexiong.mapper")
public class ShuShanApplication {private static Logger LOGGER = Logger.getLogger(ShuShanApplication.class.getName());public static void main(String[] args) {SpringApplication.run(ShuShanApplication.class, args);}@Beanpublic Javalin init(){Javalin app = Javalin.create(/*config*/).get("/", ctx -> ctx.result("Hello World")).start(7070);return app;}
}
逆向工程工具:
package com.kexuexiong.common.utils;import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.ColumnConfig;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.zaxxer.hikari.HikariDataSource;public class Codegen {public static void main(String[] args) {//配置数据源HikariDataSource dataSource = new HikariDataSource();dataSource.setJdbcUrl("jdbc:mysql://数据库ip:3306/shushan?characterEncoding=utf-8");dataSource.setUsername("root");dataSource.setPassword("密码");//创建配置内容,两种风格都可以。GlobalConfig globalConfig = createGlobalConfigUseStyle1();//GlobalConfig globalConfig = createGlobalConfigUseStyle2();//通过 datasource 和 globalConfig 创建代码生成器Generator generator = new Generator(dataSource, globalConfig);//生成代码generator.generate();}public static GlobalConfig createGlobalConfigUseStyle1() {//创建配置内容GlobalConfig globalConfig = new GlobalConfig();//设置根包globalConfig.setBasePackage("com.kexuexiong");//设置表前缀和只生成哪些表globalConfig.setGenerateSchema("shushan");globalConfig.setTablePrefix("");globalConfig.setGenerateTable("demo");//设置生成 entity 并启用 LombokglobalConfig.setEntityGenerateEnable(true);globalConfig.setEntityWithLombok(true);//设置生成 mapperglobalConfig.setMapperGenerateEnable(true);globalConfig.setAuthor("kexuexiong");globalConfig.setControllerGenerateEnable(true);globalConfig.setServiceGenerateEnable(true);globalConfig.setMapperXmlGenerateEnable(true);globalConfig.setMapperXmlPath("src/main/resources/mappers");globalConfig.setServiceImplGenerateEnable(true);//可以单独配置某个列ColumnConfig columnConfig = new ColumnConfig();columnConfig.setLarge(true);columnConfig.setVersion(true);return globalConfig;}public static GlobalConfig createGlobalConfigUseStyle2() {//创建配置内容GlobalConfig globalConfig = new GlobalConfig();//设置根包globalConfig.getPackageConfig().setBasePackage("com.kexuexiong");//设置表前缀和只生成哪些表,setGenerateTable 未配置时,生成所有表globalConfig.getStrategyConfig().setGenerateSchema("shushan").setTablePrefix("").setGenerateTable("demo");//设置生成 entity 并启用 LombokglobalConfig.enableEntity().setWithLombok(true);//设置生成 mapperglobalConfig.enableMapper();//可以单独配置某个列ColumnConfig columnConfig = new ColumnConfig();columnConfig.setColumnName("tenant_id");columnConfig.setLarge(true);columnConfig.setVersion(true);globalConfig.getStrategyConfig().setColumnConfig("account", columnConfig);return globalConfig;}
}
运行该工具类可以生成代码:
编写controller类:
package com.kexuexiong.controller;import cn.hutool.json.JSONUtil;
import com.kexuexiong.entity.Demo;
import com.kexuexiong.service.DemoService;
import io.javalin.Javalin;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.List;@Component
@Slf4j
public class DemoController {@Autowiredprivate Javalin app;@Autowiredprivate DemoService demoService;@PostConstructpublic void test(){app.get("/hello/{name}", ctx -> {List<Demo> list = demoService.list();log.info(JSONUtil.toJsonStr(list.toString()));ctx.result("Hello: ");});}
}
启动程序:
Javalin应用在一些小项目还是可以的,轻量级。