Avatar ·

How to properly use Spring annotations (@Autowired, @Component) in Kotlin?

Hello everyone! I just started learning Kotlin and am trying to migrate my old Spring project from Java to this language. I ran into a problem: Spring annotations like @Autowired don't work the way I'm used to in Java.

In Java I usually did this:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public String getUserName(Long id) {
        return userRepository.findById(id).map(User::getName).orElse("Unknown");
    }
}

When I tried to write the same thing in Kotlin:

@Service
class UserService {
    @Autowired
    private lateinit var userRepository: UserRepository
    
    fun getUserName(id: Long): String {
        return userRepository.findById(id).map { it.nam