面试题答案
一键面试依赖注入常见方式
- 构造函数注入:通过类的构造函数传递依赖。
- 属性注入:直接在类的属性上进行依赖注入。
- 方法注入:通过类的方法来设置依赖。
构造函数注入示例
假设我们有一个服务接口 MyService
及其实现类 MyServiceImpl
,以及一个使用该服务的类 MyController
。
- 定义服务接口
interface MyService {
fun doSomething(): String
}
- 实现服务接口
class MyServiceImpl : MyService {
override fun doSomething(): String {
return "Service doing something"
}
}
- 通过构造函数注入服务
import org.springframework.stereotype.Component
@Component
class MyController(private val myService: MyService) {
fun performAction() {
val result = myService.doSomething()
println(result)
}
}
在上述代码中,MyController
通过构造函数接收 MyService
的实例,实现了构造函数注入。