Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
fun getStudents()=students
-
- addStudent: This method will add a student to our database:
fun addStudent(student: Student): Boolean {
students.add(student)
return true
}
- Now let's put this database to use. We will be creating a REST controller that will handle the request. We will create a StudentController and annotate it with @RestController. Using @RestController is simple, and it's the preferred method for creating MVC RESTful web services.
- Once created, we need to provide our database using Spring dependency injection, for which we will need the @Autowired annotation. Here's how our StudentController looks:
@RestController
class StudentController {
@Autowired
private lateinit var database: StudentDatabase
}
- Now we will set our response to the / path. We will show the list of students in our database. For that, we will simply create a method that lists out students. We will need to annotate it with @RequestMapping and provide parameters such as path and request method (GET, POST, and such):
@RequestMapping("", method = arrayOf(RequestMethod.GET))
fun students() = database.getStudents()
- This is what our controller looks like now. It is a simple REST controller:
package college
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
@RestController
class StudentController {
@Autowired
private lateinit var database: StudentDatabase
@RequestMapping("", method = arrayOf(RequestMethod.GET))
fun students() = database.getStudents()
}
- Now when you restart the server and go to http://localhost:8080, we will see the response as follows:
As you can see, Spring is intelligent enough to provide the response in the JSON format, which makes it easy to design APIs.
- Now let's try to create another endpoint that will fetch a student's details from a roll number:
@GetMapping("/student/{roll_number}")
fun studentWithRollNumber( @PathVariable("roll_number") roll_number:String) =
database.getStudentWithRollNumber(roll_number)
- Now, if you try the http://localhost:8080/student/2013001 endpoint, you will see the given output:
{"roll_number":"2013001","name":"Aanand Shekhar Roy"}
- Next, we will try to add a student to the database. We will be doing it via the POST method:
@RequestMapping("/add", method = arrayOf(RequestMethod.POST))
fun addStudent(@RequestBody student: Student) =
if (database.addStudent(student)) student
else throw Exception("Something went wrong")
There's more…
So far, our server has been dependent on IDE. We would definitely want to make it independent of an IDE. Thanks to Gradle, it is very easy to create a runnable JAR just with the following:
./gradlew clean bootRepackage
The preceding command is platform independent and uses the Gradle build system to build the application. Now, you just need to type the mentioned command to run it:
java -jar build/libs/gs-rest-service-0.1.0.jar
You can then see the following output as before:
Started AppKt in 4.858 seconds (JVM running for 5.548)
This means your server is running successfully.
Creating the Application class for Spring Boot
The SpringApplication class is used to bootstrap our application. We've used it in the previous recipes; we will see how to create the Application class for Spring Boot in this recipe.
We will be using IntelliJ IDE for coding purposes. To set up the environment, read previous recipes, especially the Setting up dependencies for building RESTful services recipe.
How to do it…
If you've used Spring Boot before, you must be familiar with using @Configuration, @EnableAutoConfiguration, and @ComponentScan in your main class. These were used so frequently that Spring Boot provides a convenient @SpringBootApplication alternative. The Spring Boot looks for the public static main method, and we will use a top-level function outside the Application class.
If you noted, while setting up the dependencies, we used the kotlin-spring plugin, hence we don't need to make the Application class open.
Here's an example of the Spring Boot application:
package college
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class Application
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}
The Spring Boot application executes the static run() method, which takes two parameters and starts a autoconfigured Tomcat web server when Spring application is started.
When everything is set, you can start the application by executing the following command:
./gradlew bootRun
If everything goes well, you will see the following output in the console:
This is along with the last message—Started AppKt in xxx seconds. This means that your application is up and running.
In order to run it as an independent server, you need to create a JAR and then you can execute as follows:
./gradlew clean bootRepackage
Now, to run it, you just need to type the following command:
java -jar build/libs/gs-rest-service-0.1.0.jar
We learned how to set up dependencies for building RESTful services, creating a REST controller, and creating the application class for Spring boot. If you are interested in learning more about Kotlin then be sure to check out the 'Kotlin Programming Cookbook'.
Build your first Android app with Kotlin
5 reasons to choose Kotlin over Java
Getting started with Kotlin programming
Forget C and Java. Learn Kotlin: the next universal programming language