In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of seamless integration and perfect integration of Spring Boot and Kotlin, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.
Environmental dependence
Modify the POM file to add spring boot dependencies.
Org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc
Next, we need to add mysql dependencies.
Mysql mysql-connector-java 5.1.35 com.alibaba druid 1.0.14
Finally, add Kotlin dependencies.
Org.jetbrains.kotlin kotlin-stdlib-jdk8 org.jetbrains.kotlin kotlin-reflect org.jetbrains.kotlin kotlin-stdlib
Note that in Kotlin, data class does not have a no-parameter constructor by default, and data class defaults to type final and cannot be inherited. Note that if we use the Spring + Kotlin pattern, we may encounter this problem with @ autowared. Therefore, we can add NoArg to generate a no-parameter constructor for the annotated class. Use AllOpen to remove final from the annotated class, allowing inheritance.
Kotlin-maven-plugin org.jetbrains.kotlin ${kotlin.version} compile compile test-compile test-compile org.jetbrains.kotlin kotlin-maven-noarg ${kotlin.version} org.jetbrains.kotlin kotlin-maven-allopen ${kotlin.version}
At this point, the dependent environment for our Maven is roughly configured. The complete source code can be found in the GitHub warehouse at the end of the article.
Data source scenario 1 uses the default configuration of Spring Boot
Using the default configuration of Spring Boot, there is no need to create Bean for dataSource and jdbcTemplate.
Configure data source information in src/main/resources/application.properties.
Manual creation of spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3307/springboot_dbspring.datasource.username=rootspring.datasource.password=root scenario 2
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 = envested room.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}} script initialization
Initialize the SQL script that you need to use first.
CREATE DATABASE / *! 32312 IF NOT EXISTS*/ `springboot _ db` / *! 40100 DEFAULT CHARACTER SET utf8 * /; USE `springboot db`; DROP TABLE IF EXISTS `tauthor`; CREATE TABLE `tauthor` (`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; uses JdbcTemplate to manipulate entity objects
Class Author {var id: Long? = null var realName: String? = null var nickName: String? = null} DAO related
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}
Let's define the implementation class, through the data access operations defined by 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 (" select * from t_author where id =? ", arrayOf (id), BeanPropertyRowMapper (Author::class.java)) return list?.get (0) } override fun findAuthorList (): List {return jdbcTemplate.query ("select * from t_author", arrayOf (), BeanPropertyRowMapper (Author::class.java))}} Service related
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}
Let's define the implementation class, and the Service layer calls the methods of the Dao layer, which 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 {return this.authorDao.findAuthorList ()}} Controller related
To show the effect, let's 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 {val authorList = this.authorService.findAuthorList () val param = HashMap () 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")}} / * deletion 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) {SpringApplication.run (SpringKotlinApplication::class.java, * args)}} about testing
Here, the author recommends IDEA's Editor REST Client. IDEA's Editor REST Client has been supported since IntelliJ IDEA 2017.3, and a lot of features have been added in 2018.1. In fact, it is the HTTP Client plug-in for IntelliJ IDEA. See the author's previous article: quickly testing new skills in the API interface
# 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 # New 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"} # deletion method DELETE http://localhost:8080/authors/21Accept: application/jsonContent-Type: application/json Charset=UTF-8 thank you for reading this article carefully. I hope the article "sample Analysis of Seamless Integration and perfect Integration of Spring Boot and Kotlin" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.