Preface
This article explains how to use Kotlin under the basics of Spring Boot2, and seamlessly integrate and perfectly blend. In order to make readers more familiar with Kotlin's syntactic sugar, the author will talk about Kotlin's new features and syntactic sugar in several future articles. I won't say much below, let's take a look at the detailed introduction
Modify the POM file and add spring boot dependencies.
<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>
Immediately afterwards, we need to add mysql dependencies.
<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>
Finally, add the Kotlin dependency.
<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>
Note that in Kotlin, data class does not have a parameterless constructor by default, and data class defaults to final type and cannot be inherited. Note that if we use Spring + Kotlin mode, then using @autowared may encounter this problem. Therefore, we can add NoArg to generate parameterless constructors as the annotated class. Use AllOpen to remove final for the annotated class and allow inheritance.
<plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <version>${kotlin.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> </execution> </execution> </execution> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-noarg</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-alopen</artifactId> <version>${kotlin.version}</version> </dependency> </dependencies></plugin>At this point, our Maven's dependency environment has been roughly configured. For the complete source code, you can refer to the GitHub repository at the end of the article.
Using Spring Boot default configuration, you do not need to create a dataSource and jdbcTemplate bean.
Configure data source information in src/main/resources/application.properties.
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3307/springboot_dbspring.datasource.username=rootspring.datasource.password=root
Configure data source information in src/main/resources/config/source.properties.
# mysqlsource.driverClassName = com.mysql.jdbc.Driversource.url = jdbc:mysql://localhost:3306/springboot_dbsource.username = rootsource.password = root
Here, create dataSource and jdbcTemplate.
@Configuration@EnableTransactionManagement@PropertySource(value = *arrayOf("classpath:config/source.properties"))open class BeanConfig { @Autowired private lateinit var env: Environment @Bean open fun dataSource(): DataSource { val dataSource = DruidDataSource() dataSource.driverClassName = env!!.getProperty("source.driverClassName").trim() dataSource.url = env.getProperty("source.url").trim() dataSource.username = env.getProperty("source.username").trim() dataSource.password = env.getProperty("source.password").trim() return dataSource } @Bean open fun jdbcTemplate(): JdbcTemplate { val jdbcTemplate = JdbcTemplate() jdbcTemplate.dataSource = dataSource() return jdbcTemplate }}First initialize the required SQL script.
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 'User ID', `real_name` varchar(32) NOT NULL COMMENT 'User name', `nick_name` varchar(32) NOT NULL COMMENT 'User anonymous', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
class Author { var id: Long? = null var realName: String? = null var nickName: String? = null} 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>}Let's define the implementation class and access the data through JdbcTemplate.
@Repositoryopen 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 = jdbcTemplate.query<Author>("select * from t_author where id = ?", arrayOf<Any>(id), BeanPropertyRowMapper(Author::class.java)) return list?.get(0); } override fun findAuthorList(): List<Author> { return jdbcTemplate.query("select * from t_author", arrayOf(), BeanPropertyRowMapper(Author::class.java)) }} 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>}Let's define the implementation class. The Service layer calls the Dao layer method. This is a typical routine.
@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() }}To show the effect, we first define a simple set of RESTful API interfaces for testing.
@RestController@RequestMapping(value = "/authors")class AuthorController { @Autowired private lateinit var authorService: AuthorService /** * Query user list*/ @RequestMapping(method = [RequestMethod.GET]) fun getAuthorList(request: HttpServletRequest): Map<String, Any> { val authorList = this.authorService.findAuthorList() val param = HashMap<String, Any>() param["total"] = authorList.size param["rows"] = authorList return param } /** * Query user information*/ @RequestMapping(value = "/{userId://d+}", method = [RequestMethod.GET]) fun getAuthor(@PathVariable userId: Long, request: HttpServletRequest): Author { return authorService.findAuthor(userId) ?: throw RuntimeException("Query Error") } /** * New method*/ @RequestMapping(method = [RequestMethod.POST]) fun add(@RequestBody jsonObject: JSONObject) { val userId = jsonObject.getString("user_id") val realName = jsonObject.getString("real_name") val nickName = jsonObject.getString("nick_name") val author = Author() author.id = java.lang.Long.valueOf(userId) author.realName = realName author.nickName = nickName try { this.authorService.add(author) } catch (e: Exception) { throw RuntimeException("New Error") } } /** * Update method*/ @RequestMapping(value = "/{userId://d+}", method = [RequestMethod.PUT]) fun update(@PathVariable userId: Long, @RequestBody jsonObject: JSONObject) { var author = this.authorService.findAuthor(userId) val realName = jsonObject.getString("real_name") val nickName = jsonObject.getString("nick_name") try { if (author != null) { author.realName = realName author.nickName = nickName this.authorService.update(author) } } catch (e: Exception) { throw RuntimeException("Update Error") } } /** * Delete method*/ @RequestMapping(value = "/{userId://d+}", method = [RequestMethod.DELETE]) fun delete(@PathVariable userId: Long) { try { this.authorService.delete(userId) } catch (e: Exception) { throw RuntimeException("Delete Error") } }}Finally, we run the program through SpringKotlinApplication.
@SpringBootApplication(scanBasePackages = ["com.lianggzone.demo.kotlin"])open class SpringKotlinApplication{ fun main(args: Array<String>) { SpringApplication.run(SpringKotlinApplication::class.java, *args) }}Here, the author recommends IDEA's Editor REST Client. IDEA's Editor REST Client has been supported in IntelliJ IDEA 2017.3 version, and has added many features in 2018.1 version. In fact, it is an HTTP Client plugin for IntelliJ IDEA. See another previous article by me: Quickly testing new skills for API interfaces
### Query user list GET http://localhost:8080/authorsAccept : application/jsonContent-Type : application/json;charset=UTF-8 ### Query user information GET http://localhost:8080/authors/15Accept : application/jsonContent-Type : application/json;charset=UTF-8 ### Added method POST http://localhost:8080/authorsContent-Type: application/json { "user_id": "21", "real_name": "Liang Guizhao", "nick_name": "Liang Guizhao"} ### Update method PUT http://localhost:8080/authors/21Content-Type: application/json { "real_name" : "lianggzone", "nick_name": "lianggzone"} ### Delete method DELETE http://localhost:8080/authors/21Accept : application/jsonContent-Type: application/json;charset=UTF-8Through the simple case above, we found that it is very easy to integrate Kotlin by Spring Boot and simplify the initial construction and development process of Spring applications. In order to make readers more familiar with Kotlin's syntactic sugar, the author will talk about Kotlin's new features and syntactic sugar in several future articles.
source code
Related examples complete code: spring-kotlin-samples (local download)
Okay, the above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.