- Currently working for To The New as Senior Software Engineer.
- Over 5 years of experience in Spring and Java.
- Passionate about delivering knowledge sharing sessions. Refer to the link below for all my presentations. https://slides.com/pulkitpushkarna
A bit about me
What is Spring?
- The core of Spring Framework is based on the principle of Inversion of Control (IOC).
-
IOC is a technique that externalizes the creation and management of Component dependencies.
-
Spring acts like a container which provides instances of your application classes with all the dependencies they need.
-
A spring manages resorce is referred to as bean.
Kotlin
- Kotlin is a cross-platform, statically typed, general purpose language with type inference.
- Kotlin is designed to interoperate with Java
public class Tea {
public void prepareDrink(){
System.out.println("Preparing Tea....");
}
}
public class Restaurant {
private HotDrink hotDrink;
public Restaurant(HotDrink hotdrink){
this.hotDrink = hotDrink;
}
public HotDrink getHotDrink() {
return hotDrink;
}
}
@Configuration
class JavaConfig {
@Bean
HotDrink hotDrink() {
return new ExpressTea();
}
@Bean
Restaurant restaurant(HotDrink hotDrink) {
Restaurant restaurant = new Restaurant();
restaurant.setHotDrink(hotDrink);
return restaurant;
}
}
context.initializer.classes=com.jetbrainsconfdemo.kotlinwithspringboot.BeanInitializer
application.properties
Kotlin Config file
import org.springframework.context.support.beans
fun bean() = beans {}
Getting started with Kotlin Bean Configuration
Initializer class
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.support.GenericApplicationContext
class BeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {
override fun initialize(context: GenericApplicationContext) =
beans().initialize(context)
}
Java Config
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
class JavaConfig {
@Bean
@Primary
HotDrink tea() {
return new Tea();
}
@Bean("hotDrink")
HotDrink ExpressTea() {
return new ExpressTea();
}
@Bean(name = "restaurant",initMethod = "init")
@Scope("Prototype")
@Primary
Restaurant restaurant(HotDrink hotDrink) {
Restaurant restaurant = new Restaurant();
restaurant.setHotDrink(hotDrink);
return restaurant;
}
}
Kotlin Config
import org.springframework.context.support.beans
fun beans() = beans {
bean<Tea>(isPrimary = true)
bean<ExpressTea>("hotDrink")
bean<RestaurantK>(name = "restK",
initMethodName = "init",
scope = BeanDefinitionDsl.Scope.PROTOTYPE,
isPrimary = true)
}
Complex class in Java
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Complex {
List<Integer> list;
Set<Integer> set;
Map<Integer,String> map;
public Complex(List<Integer> list, Set<Integer> set, Map<INteger,String>){
this.list = list;
this.set = set;
this.map = map;
}
public List<Integer> getList() {
return list;
}
public Set<Integer> getSet() {
return set;
}
public Map<Integer, String> getMap() {
return map;
}
}
Complex Class in Kotlin
data class ComplexK(val list: List<Int>,
val set: Set<Int>,
val map: Map<Int, String>)
Java Config for Complex class
@Bean
Complex complex() {
Map map = new HashMap();
map.put(1, "One");
map.put(2, "Two");
return new Complex(Arrays.asList(1, 2, 3, 4),
new HashSet(Arrays.asList(1, 1, 2, 3, 4)),
map);
}
Kotlin Config for Complex class
bean{
ComplexK(
listOf(1,2,3,4),
setOf(1,2,2,3,4),
mapOf(1 to "One", 2 to "Two", 3 to "Three"))
}
application.properties
spring.datasource.url=jdbc:mysql://localhost/rest_with_spring
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
Exceuting code at application start up
package com.springbootwebkotlin.demo.springbootwebkotlin
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.context.support.beans
@SpringBootApplication
class SpringBootWebKotlinApplication
fun main(args: Array<String>) {
SpringApplicationBuilder()
.initializers(beans {
bean {
ApplicationRunner{
println("Application Started")
}
}
}).sources(SpringBootWebKotlinApplication::class.java).run(*args)
}
Creating Hibernate Entity
import javax.persistence.Entity
import javax.persistence.Id
@Entity
data class Employee(@Id val id: Int,
val name: String, val age: Int)
import org.springframework.data.repository.CrudRepository
interface EmployeeRepository : CrudRepository<Employee, Int>
Creating Employee Repository
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.context.support.beans
@SpringBootApplication
class SpringBootWebKotlinApplication
fun main(args: Array<String>) {
SpringApplicationBuilder()
.initializers(beans {
bean {
ApplicationRunner {
println("Bootstrap Data....")
val employeeRepository = ref<EmployeeRepository>()
if(employeeRepository.count()==0L) {
listOf(Employee(1, "name1", 21),
Employee(2, "name2", 22),
Employee(3, "name3", 23))
.forEach { e -> employeeRepository.save(e) }
println("Total number of employees saved : ${employeeRepository.count()}")
}
}
}
}).sources(SpringBootWebKotlinApplication::class.java).run(*args)
}
import org.springframework.data.repository.CrudRepository
interface EmployeeRepository : CrudRepository<Employee, Int> {
fun findByName(name: String) : Employee
}
import org.springframework.data.repository.query.Param
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/employee")
class EmployeeController(val employeeRepository: EmployeeRepository) {
@RequestMapping
fun getEmployee() = employeeRepository.findAll()
@RequestMapping("/{id}")
fun findById(@PathVariable id: Int) = employeeRepository.findById(id);
@RequestMapping("/findByName")
fun findByName(@Param("name") name: String)
= employeeRepository.findByName(name)
}
Spring and Kotlin
By Pulkit Pushkarna
Spring and Kotlin
- 942