https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
spring
  • p

    Paul N

    06/17/2020, 11:18 AM
    If I want to use Spring retry in Java I do this, with "@BackOff". If I paste the same annotation on a Kotlin function it complains about the @ sign with "an annotation can't be used as the annotations argument, so I have to remove the @ sign which is what also happens if I convert the Java to Kotlin Why is this and will the Kotlin work without the @ sign ? Kotlin:
    @Retryable(backoff = @Backoff(delay = 2222)) // won't compile
        fun doIt() {
        }
    Java:
    public class Delme {
    
        @Retryable(backoff = @Backoff(delay = 2222))
        void doIt() {
    
        }
    }
    k
    t
    • 3
    • 4
  • s

    Shawn A

    06/22/2020, 10:55 PM
    This isn't specific to Kotlin but maybe someone knows. I cannot get spring to bind a query string to a nested object when using WebFlux. An example I threw together:
    @GetMapping("/api/users")
    fun getAll(user: User) = Mono.just(user)
    -- snip --
    
    data class User(
        val firstName: String,
        val address: Address
    )
    
    data class Address(
        val street: String
    )
    Curl:
    curl '<http://localhost:8080/api/users?firstName=shawn&address.street=foo>'
    500 error:
    org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.expediagroup.application.User]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Parameter specified as non-null is null: method com.expediagroup.application.User.<init>, parameter address
    I am pretty sure this works with the servlet API.
    t
    w
    • 3
    • 5
  • a

    ashmelev

    06/23/2020, 12:40 AM
    I think you need
    fun getAll(@RequestBody @Validated user: User).....
    w
    • 2
    • 1
  • i

    Iain Cambridge

    06/23/2020, 4:00 PM
    Can anyone help explain why my validation isn't working?
    data class Credential(
            @field:JsonProperty("country_code")
            @field:Pattern(regexp = "^[A-Z]{2}$", message = "country_code must be a string of 2 capital letters i.e. DE")
            val countryCode: String? = null,
    )
    With
    fun registerCredentials(@Validated @RequestBody credential: Credential):Credential{ 
       //...
    }
    I've tried
    @Valid
    and that doesn't work either. I don't get any error, I just ged a object with null values.
    t
    • 2
    • 2
  • m

    Marian Schubert

    06/27/2020, 7:38 PM
    I would like to bootstrap my Spring application/context in tests programatically (not via SprintTest JUnit annotation) - any idea how to do that? Googling is failing me 🙂 Any pointers would be appreciated.
    t
    f
    • 3
    • 2
  • s

    Stian N

    06/29/2020, 10:57 AM
    How do you extract the body from a ResponeEntity<> with type safety? getBody() has a
    object?
    signature, and you can work around this with
    !!
    . Is this the prefered method?
    k
    f
    m
    • 4
    • 7
  • a

    Ashish Kumar Joy

    06/29/2020, 5:40 PM
    Is there a way in SpringWebFlux to get current Http Request object in a class apart from the controller and webfilter. Something similar to ServerRequestContext provided by Micronaut Framework. Using that i can get hold of http request during its lifecycle.
    r
    • 2
    • 1
  • s

    Sandy

    06/30/2020, 12:09 AM
    I am trying to write integration test using @transaction annotaion. My integration test uses test containers. Whenever I remove the tranasction annotation, I am able to ser data in test containers, in docker. However if i add transaction annotation, i don't see data in mysql test container. Wondering at what point does data get commited, if tranaction annotation is used at method level in a springboot integration test?
    k
    n
    • 3
    • 16
  • d

    Dennis Schröder

    07/02/2020, 11:12 AM
    What is the functional bean equivalent of constructor injection of a value
    @Value("\${some.value:default}") someValue: String
    k
    • 2
    • 3
  • b

    bjonnh

    07/08/2020, 9:02 PM
    Is it possible to use spring boot with Kotlin 1.4-M3?
    i
    m
    • 3
    • 6
  • d

    Dariusz Kuc

    07/10/2020, 9:47 PM
    hello! 👋 while working on custom
    FactoryBean
    I’m hitting some weird (at least to me) behavior - when I create the underlying object I need to configure it with some beans retrieved from application context (factory is application context aware). Weird part is the different behavior between retrieving bean by name (works - loads necessary autoconfigs) and the type (fails -> dependent config is not loaded).
    // works - dependent auto config is loaded
    val targetBean = applicationContext.getBean("targetBeanName")
    
    // blows up with no bean
    val targetBean = applicationContext.getBean(TargetBean::class.java)
    Any ideas?
    • 1
    • 3
  • i

    iari

    07/13/2020, 10:47 AM
    I have a problem with spring-data / hibernate and detached entities. This isn't particularly a kotlin-problem - but since I'm doing the whole project in kotlin, and the example code is kotlin, I'm hoping, that it is still acceptable to post this here. The gist of it is, that im calling
    val adminRole = roles.findByName("admin")!!
    val adminUser = BackendUser("admin", adminRole
        // some more data here
    )
    users.save(adminUser)
    and get org.hibernate.PersistentObjectException: detached entity passed to persist: my.package.name.user.UserRole More details are in this SO post: https://stackoverflow.com/questions/62874155/spring-data-hibernate-detached-entity-passed-to-persist Any help would be appreciated.
    k
    t
    • 3
    • 5
  • j

    Jeremy

    07/17/2020, 1:57 PM
    I'm having a problem with trying to use WebClient with Kotlin. I'm just trying to make a GET request, but I keep getting
    org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/html;charset=utf-8' not supported for bodyType
    . Here's the service:
    val client = WebClient.builder()
                    .baseUrl(apiUrl)
                    .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.ALL_VALUE)
                    .defaultHeader("X-API-TOKEN", apiToken)
                    .build()
    
            return client.get()
                    .uri("/$directoryId/mailinglists/$mailingListId")
                    .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)
                    .acceptCharset(Charset.forName("UTF-8"))
                    .retrieve()
                    .bodyToMono(GetMailingListResponse::class.java)
    Here's the controller:
    @GetMapping("/directories/{directoryId}/mailinglists/{mailingListId}")
        fun handle(@PathVariable directoryId: String, @PathVariable mailingListId: String): Mono<ResponseEntity<GetMailingListResponse>> {
            val resp = service.createMailingList(directoryId, mailingListId)
            return resp.map {
                body -> ResponseEntity.ok(body)
            }
        }
    Any help would be appreciated.
    a
    • 2
    • 1
  • h

    hooliooo

    07/21/2020, 6:21 AM
    How can I test 2nd level cache hits in a unit test? I’m using this article as a reference https://www.baeldung.com/hibernate-second-level-cache but I’m not sure how to test it because I can’t seem to get access to the Cachemanager singleton in Kotlin
    d
    • 2
    • 1
  • h

    Hanwool Seok

    07/28/2020, 10:35 AM
    Hello. I am developing spring server with kotling using VSCode. But I have problems with auto importing in vscode. Cloud anyone help me?
    k
    • 2
    • 1
  • r

    ReddyTintaya

    07/30/2020, 5:09 PM
    Hi, i'm doing an e commerce with the backend in spring and for recipes i'm returning mimeMessage emails but i'm building my htmls as strings dynamically, so it's a hard string process ... is there any library that you've used and recommend for doing this?
    k
    c
    • 3
    • 3
  • j

    Jose Antonio Jimenez

    08/04/2020, 10:51 AM
    Hi, does anyone know if `@schedule`annotation works with kotlin `suspended`functions?
    k
    • 2
    • 2
  • j

    JP

    08/04/2020, 1:35 PM
    A noob question: When using Spring’s 
    @Autowired
     with Kotlin, I’m confused whether this
    @Autowired
    private lateinit var userService: UserService
    is a field injection or a setter injection. In the documentation, the Kotlin equivalent of both field and setter injection of Java were all in this fashion. I read that field injection should be avoided, and I’ll try to stick with constructor injection if possible, but I’m just trying them out to learn. If there is actually like a more stricter equivalents, I’d like to know how to write them in Kotlin. Can anyone shed some light on this to me?
    t
    e
    • 3
    • 10
  • n

    nathan

    08/13/2020, 9:10 PM
    soo im using spring boot with kotlin Entity
    @Entity
    @Table(name="storypost")
    class StoryPost(
            @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
            @Column(name = "storypost_id")
            var id: Long,
            var body: String,
            var video_link: String,
            var image_link: String,
            var likes: Int,
            @ManyToOne(fetch = FetchType.EAGER)
            @JoinColumn(name = "userprofile_id")
            @JsonBackReference
            var userProfile: UserProfile?=null
    )
    Controller
    @RestController
    class StoryPostController ( val repo : StoryPostRepositories){
    
    
        @GetMapping("/storypost")
        fun getAllStoryPosts() = repo.findAll().toList()
    
        @PostMapping("/storypost")
        fun addStoryPost(@RequestBody userPost : StoryPost) : ResponseEntity<StoryPost>{
            repo.save(userPost)
            return ResponseEntity<StoryPost>(userPost, HttpStatus.CREATED)
        }
    }
    how would I include the user id when making a storypost post request? should i just put another var
    user_id: Long
    and then have a
    val repo2 : UserRepo
    to find by id?
    g
    • 2
    • 1
  • k

    kenkyee

    08/15/2020, 11:12 AM
    In Sebastian's latest presentation, he mentioned we can help convert the Spring Boot samples to Kotlin to help his workload....anyone know how we can do that? https://blog.jetbrains.com/kotlin/2020/08/the-state-of-kotlin-support-in-spring/
    j
    s
    • 3
    • 4
  • m

    mp

    08/18/2020, 10:40 AM
    hi there. Has anyone bumped kotlin to 1.4 in SB project already? 😃
    🙋‍♂️ 1
    👍 1
    j
    r
    +2
    • 5
    • 8
  • m

    Manuel Lorenzo

    08/18/2020, 1:50 PM
    so I’d like to make several requests to several feeds to retrieve the articles of each feed and store them in my own DB
    r
    • 2
    • 1
  • m

    Manuel Lorenzo

    08/18/2020, 1:51 PM
    I’ve just developed some easy RESTful APIs but never done such thing 🙂
    m
    d
    • 3
    • 5
  • d

    Dariusz Kuc

    08/19/2020, 6:01 PM
    Hello! 👋 I’m hitting a problem with conditional bean creation order - I’m writing custom bean registrar to generate and register some beans based on the configuration properties and I provide some default beans as a fallback. Basically • I got an annotation for explicit opt-in where I import my registrar and fallback config • registrar is environment aware so it can bind my properties and uses factory bean to create target beans (e.g.
    BeanDefinitionBuilder.genericBeanDefinition(MyFactoryBean::class.java)
    •
    MyFactoryBean
    is application context aware and it attempts to retrieve
    FallbackBean
    from context (e.g. using
    applicationContext.getBean(FallbackBean::class.java)
    • within a
    @SpringBootTest
    I’m explicitly creating
    SomeBean
    in a configuration class So my problem is that conditional logic (i.e.
    @ConditionalOnBean
    ) is evaluated BEFORE attempting to create the
    SomeBean
    in test configuration…. Sample code in the thread. Any ideas what I might be missing?
    • 1
    • 2
  • x

    xii

    08/23/2020, 11:10 PM
    Hey! I've been migrating a simple project from Spring MVC to Webflux (with Netty). I did a rough load test attempt locally, to see if response times were slower, but I found they actually seem to be higher (not a lot, let's say 10-15% higher). Could this be a symptom of me doing unintentional blocking or something like that?
    k
    • 2
    • 2
  • d

    DosExe

    08/25/2020, 3:57 PM
    Hi, I have a problem with spring boot 2.1.6 I tried to use kotlin bean dsl to declare beans and it works perfectly fine for the core app, but tests are failing (for tests I am using spring-boot-starter-test and kotest). I have read all the information I could find on stackoverflow and made these improvements: 1. Created
    class BeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {
       override fun initialize(context: GenericApplicationContext) {
           beans().initialize(context)
       }
    }
    2. Set context.initializer.classes=com.package.BeansInitializer in application.properties It helped a little bit, now some of the beans are created, but all beans with @ConfigurationsProperties are still not created.
    👀 1
    t
    • 2
    • 3
  • d

    Dariusz Kuc

    08/27/2020, 2:46 PM
    hello! 👋 Is there are preferred visibility modifier for creating auto configuration libs? My co-worker insists on making those internal which seems wrong to me….
    w
    k
    • 3
    • 5
  • a

    Ayodele

    08/29/2020, 9:13 AM
    Hi guys I'm having issues with the mapstruct mapper in springboot
    @Mapper
    @Component
    interface UserMapper {
        fun toUserDTO(user: User): UserDTO
        fun toListOfUserDTO(users: List<User>) : List<UserDTO>
        fun toUser(userDTO: UserDTO) : User
        fun toListOfUser(userDTOs: List<UserDTO>) : List<User>
    }
    and i'm using it in my contoller
    @Autowired
    lateinit var userMapper: UserMapper
    It gives this error, please help
    ***************************
    APPLICATION FAILED TO START *************************** Description: Field userMapper in com.scienta.backend_rated_ng.controller.AuthController required a bean of type 'com.scienta.backend_rated_ng.mapper.UserMapper' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true) Action: Consider defining a bean of type 'com.scienta.backend_rated_ng.mapper.UserMapper' in your configuration. I have all my dependencies right
    t
    • 2
    • 30
  • p

    Philipp Mayer

    08/29/2020, 5:38 PM
    Hi! I'm playing around with the router dsl and its working great so far. However, I want to set up my Controller which handles thymeleaf too. I got this GET Endpoint:
    @GetMapping("/")
        fun index(model: Model): String {
            model.addAttribute(....)
            return "index"
        }
    and I would like to convert it to the new dsl.
    router {
            accept(MediaType.TEXT_HTML).nest {
                GET("/") { index(/*model param missing*/) }
            }
    Could one give me a hint how to handle the parameter
    model: Model
    accordingly? Thanks a lot!
    j
    • 2
    • 1
  • n

    nathan

    09/01/2020, 2:25 AM
    where do u recommend deploying spring boot
    a
    • 2
    • 1
Powered by Linen
Title
n

nathan

09/01/2020, 2:25 AM
where do u recommend deploying spring boot
a

AlexJuca

09/05/2020, 9:30 AM
azure would be a good option.
View count: 4