如何在kotlin中使用@Autowired这样的Spring注解?
是否有可能在Kotlin做下面的事情?
@Autowired internal var mongoTemplate: MongoTemplate @Autowired internal var solrClient: SolrClient
当然,这是可能的,你有几个选项,我建议带注释的构造函数,但是lateinit也可以,在一些情况下可能有用:
Lateinit:
@Component class YourBean { @Autowired lateinit var mongoTemplate: MongoTemplate @Autowired lateinit var solrClient: SolrClient }
构造函数:
@Component class YourBean @Autowired constructor( private val mongoTemplate: MongoTemplate, private val solrClient: SolrClient ) { // code }
Spring 4.3的构造函数:
@Component class YourBean( private val mongoTemplate: MongoTemplate, private val solrClient: SolrClient ) { // code }
构造器版本检查所有依赖关系在创建bean的时候和所有注入的字段 – val,在另一方面,lateinit注入的字段只能是var,并且运行时占用的空间很小。 而用测试类来测试,你不需要反思。
链接:
- 关于lateinit的文档
- 关于构造函数的文档
- 用Kotlin开发Spring Boot应用程序
是的,Java注释在Kotlin中大部分都支持Java。 一个问题是主构造函数中的注释需要显式的“构造函数”关键字:
从https://kotlinlang.org/docs/reference/annotations.html
如果您需要注释类的主构造函数,则需要将构造函数关键字添加到构造函数声明中,并在其之前添加注释:
class Foo @Inject constructor(dependency: MyDependency) { // ... }
- 如何将IoC注入到Kotlin顶级函数中? 我甚至使用IoC容器?
- Kotlin无法在类中使用@Configuration @EnableWebMvc注释创建@Autowired字段
- Kotlin NoClassDefFoundError和spring @RequestMapping方法
- 在Kotlin中使用@Service时引发异常
- 在运行时生成的类中使用Kotlin对象
- 使用Spring HATEOAS ControllerLinkBuilder和Kotlin抛出IllegalArgumentException
- 用Spring 5 WebFlux框架解码ByteArray
- Spring @PostConstruct取决于@Profile
- 找到未索引的远程资源库