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 code
ctx.json(object);
});
app.post("/input", ctx -> {
// some code
ctx.status(201);
});
Javalin官网文档地址
下面基于Javalin和springboot、Mybatis-Flex(Mybatis-Flex官网文档)实现一个简单的项目:
项目结构:
pom.xml
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>3.1.2version>
<relativePath/>
parent>
<groupId>com.kexuexionggroupId>
<artifactId>shushan_serverartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<java.version>17java.version>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
<dependency>
<groupId>com.mybatis-flexgroupId>
<artifactId>mybatis-flex-spring-boot-starterartifactId>
<version>1.5.3version>
dependency>
<dependency>
<groupId>com.mybatis-flexgroupId>
<artifactId>mybatis-flex-processorartifactId>
<version>1.5.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.20version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>io.javalingroupId>
<artifactId>javalinartifactId>
<version>5.6.1version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starter-testartifactId>
<version>3.0.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.zaxxergroupId>
<artifactId>HikariCPartifactId>
<version>4.0.3version>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.16version>
dependency>
<dependency>
<groupId>com.mybatis-flexgroupId>
<artifactId>mybatis-flex-codegenartifactId>
<version>1.5.3version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-simpleartifactId>
<version>2.0.7version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
application.yml
spring:
datasource:
url: jdbc:mysql://数据库ip:3306/shushan
username: root
password: 密码
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);
}
@Bean
public 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 并启用 Lombok
globalConfig.setEntityGenerateEnable(true);
globalConfig.setEntityWithLombok(true);
//设置生成 mapper
globalConfig.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 并启用 Lombok
globalConfig.enableEntity()
.setWithLombok(true);
//设置生成 mapper
globalConfig.enableMapper();
//可以单独配置某个列
ColumnConfig columnConfig = new ColumnConfig();
columnConfig.setColumnName("tenant_id");
columnConfig.setLarge(true);
columnConfig.setVersion(true);
globalConfig.getStrategyConfig()
.setColumnConfig("account", columnConfig);
return globalConfig;
}
}
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 {
@Autowired
private Javalin app;
@Autowired
private DemoService demoService;
@PostConstruct
public void test(){
app.get("/hello/{name}", ctx -> {
List<Demo> list = demoService.list();
log.info(JSONUtil.toJsonStr(list.toString()));
ctx.result("Hello: ");
});
}
}