Kotlin has released version 1.1.0 and is already fascinated by its advanced syntax. Instead of stating how powerful Kotlin is, I’ll show you how to integrate with SpringBoot.

Demo address: github.com/gefangshuai…

Step 1: Get the project scaffolding

IO customized download the basic prototype of the project, my configuration is as follows:





basic

After downloading it, import it into Idea and set up the basic directory structure as follows:





Paste_Image.png

Environment to prepare

Add JSP support

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>Copy the code

Added postgresQL database support

<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.3-1102. Jdbc41</version>
</dependency>Copy the code

Add developer tools

For automatic deployment

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>Copy the code

Enable view and JPA support

Modify the application.properties file as follows:

server.port=8082

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

spring.devtools.restart.exclude=static/**,public/**

# database
spring.datasource.url= jdbc:postgresql://localhost:5432/test
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# jpa+hibernate
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=true
spring.jpa.show-sql = trueCopy the code

At this point, the project environment is ready.

The business development

Let’s do some simple business development.

Structural Model class

Suppose we want to maintain a customer information that contains two pieces of information “firstName” and “lastName.” The model class is as follows:

@Entity
@Table(name = "customer")
data class Customer ( @Id @GeneratedValue(strategy = GenerationType.AUTO)var id: Int? , var firstName: String? , var lastName: String? ){
    constructor() : this(null.null.null)  / / Spring
}Copy the code

Here we use Kotlin’s data class, because normally our Model class is just used to store data and does little business. The benefits of using data classes are as follows: Equals (), hashCode(), toString()componentN(), and copy() are generated automatically. See also: kotlin – ZHCN. Making. IO/docs/refere…

Notice here

  1. In the JVM, if the generated class needs to have a constructor with no arguments, all attributes must be specified with default values. (See constructor).

    data class User(val name: String = "", val age: Int = 0)Copy the code

    Because Spring requires the Model class to have a no-argument construct when it comes to object binding, the Customer class we declare here must specify a construction parameter default. Otherwise, Spring will fail to bind objects!!

  2. Since Spring dependency injection requires a default no-parameter construction, we need to create a default no-parameter constructor for it

    constructor() : this(null.null.null)Copy the code

    Of course, Kotlin gave us tool support to solve this rather trivial problem. Here’s how Maven is configured:

    <dependency>
       <groupId>org.jetbrains.kotlin</groupId>
       <artifactId>kotlin-maven-noarg</artifactId>
       <version>${kotlin.version}</version>
    </dependency>Copy the code

    Enable JPA support:





    Paste_Image.png

So we don’t have to actively implement the empty construct when we write the Model class. The compiler will do it for us

@Entity
@Table(name = "customer")
data class Customer (
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        var id: Int? , varfirstName: String? , varlastName: String? ) : Serializable{// Constructor () : this(null, null, null
}Copy the code

Prepare Dao class

interface CustomerRepository : CrudRepository<Customer.Long> {
    fun findByLastName(lastName: String): MutableIterable<Customer>

}Copy the code

As you can see, the difference between Kotlin and Java syntax is the same.

Write the Service class

@Service
@Transactional(readOnly = true)
class CustomerService {
    @Autowired
    lateinit var customerReposity: CustomerRepository

    @Transactional
    fun save(customer: Customer) = customerReposity.save(customer)

    fun findAll(a): MutableIterable<Customer>? = customerReposity.findAll();

}Copy the code

CustomerController class

@Controller
@RequestMapping("/customer")
class CustomerController {
    @Autowired
    lateinit var customerService: CustomerService

    @RequestMapping("/add")
    fun addForm(a): String = "form"

    @RequestMapping(value = "save", method = arrayOf(RequestMethod.POST))
    fun saveCustomer(customer: Customer): String {
        customerService.save(customer)

        return "redirect:/"}}Copy the code

Note: In Controller we inject Service using Kotlin’s attribute lazy loading mechanism

lateinit var customerService: CustomerServiceCopy the code

Because Spring instantiates services and other beans for us. Other also is the distinction on grammar, what do not understand can fill the brain by oneself.

View page is no longer introduced, you can download the project to see the specific code: github.com/gefangshuai…

Run the example

The Maven configuration is as follows:





Maven configuration

After running, you will see the home page





Home page

Click Add to jump to add Form page:





The form

Submitting the form will refresh the home page with the information we added





The list of

conclusion

Source code address: SpringBoot Kotlin Demo

Ok, so a simple Kotlin+SpringBoot Demo has been developed, and you can use this project as a basic prototype for further business expansion. Kotlin’s 100% Interoperable with Java™ principle makes up for a lot of Java’s shortcomings and is definitely a new language worth learning and using.

What do you think of Kotlin? Here’s a joke: with val, you don’t have to worry about static final and final static. : -)