Code前端首页关于Code前端联系我们

如何使用Kotlin基于Spring Boot2并完美结合

terry 2年前 (2023-09-23) 阅读数 71 #移动小程序

讲解如何使用Kotlin基于Spring Boot2并无缝集成、完美结合。

环境依赖

编辑POM文件并添加spring boot依赖。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
</dependencies>
复制代码

接下来我们需要添加mysql依赖。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.35</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.14</version>
</dependency>
复制代码

最后,增加对Kotlin的依赖。

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
</dependency>
复制代码

注意,在Kotlin中,数据类默认没有无参构造函数,并且数据类默认为final类型,不能被继承。请注意,如果我们使用 Spring + Kotlin 模型,则在使用 @autowared 时可能会遇到此问题。因此,我们可以添加 NoArg 并为带注释的类生成一个不带参数的构造函数。使用 AllOpen 从带注释的类中删除 Final 并启用其继承。

<plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <groupId>org.jetbrains.kotlin</groupId>
    <version>${}</version>
    <executions>
        <execution>
            <id>compile</id>
            <goals> <goal>compile</goal> </goals>
        </execution>
        <execution>
            <id>test-compile</id>
            <goals> <goal>test-compile</goal> </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-noarg</artifactId>
            <version>${}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>${}</version>
        </dependency>
    </dependencies>
</plugin>
复制代码

至此,我们的Maven依赖环境就大致配置完成了。完整的源代码可以在文章末尾的 GitHub 存储库中找到。

数据源

选项1 使用默认的Spring Boot配置

使用默认的Spring Boot配置时,不需要为dataSource和jdbcTemplate创建bean。

src/main/resources/中配置数据源信息。

<pre>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.data=jdbc:mysql://localhost:3307/springboot_db
spring.data=root
spring.data=root
</pre>
复制代码

方案2:手动创建

,并在src/main/resources/config/中配置数据源信息。


 = com.mysql.jdbc.Driver
 = jdbc:mysql://localhost:3306/springboot_db
 = root
 = root
复制代码

在此创建dataSource和jdbcTemplate。

@Configuration
@EnableTransactionManagement
@PropertySource(value = *arrayOf("classpath:config/"))
open class BeanConfig {
    @Autowired
    private lateinit var env: Environment
    @Bean
    open fun dataSource(): DataSource {
        val dataSource = DruidDataSource()
        dataSource.driverClassName = env!!.getProperty("").trim()
        dataSource.url = env.getProperty("").trim()
        dataSource.username = env.getProperty("").trim()
        dataSource.password = env.getProperty("").trim()
        return dataSource
    }
    @Bean
    open fun jdbcTemplate(): JdbcTemplate {
        val jdbcTemplate = JdbcTemplate()
        jdbcTemplate.dataSource = dataSource()
        return jdbcTemplate
    }
}
复制代码

初始化脚本

首先初始化您需要使用的SQL脚本。

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `springboot_db`;
DROP TABLE IF EXISTS `t_author`;
CREATE TABLE `t_author` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
复制代码

使用JdbcTemplate控制

interface AuthorDao {
    fun add(author: Author): Int
    fun update(author: Author): Int
    fun delete(id: Long): Int
    fun findAuthor(id: Long): Author?
    fun findAuthorList(): List<Author>
}
复制代码

相关的实体对象

class Author {
    var id: Long? = null
    var realName: String? = null
    var nickName: String? = null
}
复制代码

我们定义一个实现类,并使用JdbcTemplate定义的数据访问操作。

@Repository
open class AuthorDaoImpl : AuthorDao {
    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate
    override fun add(author: Author): Int {
        return jdbcTemplate.update("insert into t_author(real_name, nick_name) values(?, ?)",
                author.realName, author.nickName)
    }
    override fun update(author: Author): Int {
        return jdbcTemplate.update("update t_author set real_name = ?, nick_name = ? where id = ?",
                *arrayOf(author.realName, author.nickName, author.id))
    }
    override fun delete(id: Long): Int {
        return jdbcTemplate.update("delete from t_author where id = ?", id)
    }
    override fun findAuthor(id: Long): Author? {
        val list = ("select * from t_author where id = ?",
                arrayOf<Any>(id), BeanPropertyRowMapper(Author::))
        return list?.get(0);
    }
    override fun findAuthorList(): List<Author> {
        return jdbcTemplate.query("select * from t_author", arrayOf(), BeanPropertyRowMapper(Author::))
    }
}
复制代码

服务相关

interface AuthorService {
    fun add(author: Author): Int
    fun update(author: Author): Int
    fun delete(id: Long): Int
    fun findAuthor(id: Long): Author?
    fun findAuthorList(): List<Author>
}
复制代码

让我们定义一个实现类。 Service层调用Dao层的方法。这是一个典型的例行公事。

@Service("authorService")
open class AuthorServiceImpl : AuthorService {
    @Autowired
    private lateinit var authorDao: AuthorDao
    override fun update(author: Author): Int {
        return this.authorDao.update(author)
    }
    override fun add(author: Author): Int {
        return this.authorDao.add(author)
    }
    override fun delete(id: Long): Int {
        return this.authorDao.delete(id)
    }
    override fun findAuthor(id: Long): Author? {
        return this.authorDao.findAuthor(id)
    }
    override fun findAuthorList(): List<Author> {
        return this.authorDao.findAuthorList()
    }
}
复制代码

控制器相关

为了展示效果,我们首先定义一组简单的RESTful API来进行测试。

@RestController
@RequestMapping(value = "/authors")
class AuthorController {
    @Autowired
    private lateinit var authorService: AuthorService
    /**
     * 查询用户列表
     */
    @RequestMapping(method = [])
    fun getAuthorList(request: HttpServletRequest): Map<String, Any> {
        val authorList = ()
        val param = HashMap<String, Any>()
        param["total"] = authorList.size
        param["rows"] = authorList
        return param
    }
    /**
     * 查询用户信息
     */
    @RequestMapping(value = "/{userId:\\d+}", method = [])
    fun getAuthor(@PathVariable userId: Long, request: HttpServletRequest): Author {
        return authorService.findAuthor(userId) ?: throw RuntimeException("查询错误")
    }
    /**
     * 新增方法
     */
    @RequestMapping(method = [])
    fun add(@RequestBody jsonObject: JSONObject) {
        val userId = ("user_id")
        val realName = ("real_name")
        val nickName = ("nick_name")
        val author = Author()
        author.id = java.lang.Long.valueOf(userId)
        author.realName = realName
        author.nickName = nickName
        try {
            (author)
        } catch (e: Exception) {
            throw RuntimeException("新增错误")
        }
    }
    /**
     * 更新方法
     */
    @RequestMapping(value = "/{userId:\\d+}", method = [])
    fun update(@PathVariable userId: Long, @RequestBody jsonObject: JSONObject) {
        var author = (userId)
        val realName = ("real_name")
        val nickName = ("nick_name")
        try {
            if (author != null) {
                author.realName = realName
                author.nickName = nickName
                this.authorService.update(author)
            }
        } catch (e: Exception) {
            throw RuntimeException("更新错误")
        }
    }
    /**
     * 删除方法
     */
    @RequestMapping(value = "/{userId:\\d+}", method = [])
    fun delete(@PathVariable userId: Long) {
        try {
            (userId)
        } catch (e: Exception) {
            throw RuntimeException("删除错误")
        }
    }
}
复制代码

最后,我们通过Spring Kotlin应用程序来运行程序。

@SpringBootApplication(scanBasePackages = [""])
open class SpringKotlinApplication{
    fun main(args: Array<String>) {
        (SpringKotlinApplication::, *args)
    }
}
复制代码

关于测试

这里笔者推荐IDEA的Editor REST客户端。IntelliJ IDEA 2017.3 支持 IDEA 的 REST 客户端编辑器,并且该版本中添加了许多功能。它实际上是 IntelliJ IDEA 的 HTTP 客户端插件。参见作者之前的另一篇文章:快速API测试新技能|梁桂照博客


GET http://localhost:8080/authors
Accept : application/json
Content-Type : application/json;charset=UTF-8

GET http://localhost:8080/authors/15
Accept : application/json
Content-Type : application/json;charset=UTF-8

POST http://localhost:8080/authors
Content-Type: application/json
{
    "user_id": "21",
    "real_name": "梁桂钊",
    "nick_name": "梁桂钊"
}

PUT http://localhost:8080/authors/21
Content-Type: application/json
{
    "real_name" : "lianggzone",
    "nick_name": "lianggzone"
}

DELETE http://localhost:8080/authors/21
Accept : application/json
Content-Type : application/json;charset=UTF-8
复制代码

总结

通过上面的简单案例,我们发现将Spring Boot与Kotlin集成起来,简化Spring应用程序的初始化是非常容易的。建设和发展过程。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门