dcc*_*rmo 2 dependency-injection kotlin spring-boot
这是我得到的:
@Component
class FooController {
fun createFoo() {
val foo = FooEntity()
foo.name = "Diogo"
fooRepository.save(foo)
}
@Autowired
internal lateinit var fooRepository: FooRepository
}
Run Code Online (Sandbox Code Playgroud)
试图打电话时createFoo(),我收到以下错误:
kotlin.UninitializedPropertyAccessException: lateinit property fooRepository has not been initialized
我认为@Component在顶部添加一个可以让我的课程被Spring发现并因此@Autowired工作,但也许我弄错了?
只是添加@Component到课堂是不够的.
1)使用时@Component,必须确保通过组件扫描扫描类.这取决于您如何引导应用程序,但您可以使用<context:component-scan base-package="com.myCompany.myProject" />XML配置或@ComponentScanJava配置.
如果您正在使用Spring引导 - 您不需要声明 @ComponentScan自己,因为@SpringBootApplication继承它并且默认情况下它会扫描当前包中的所有类及其所有子包.
2)你必须从春天的背景中获取豆子.创建一个对象new将无法正常工作.
基本上有两种方法可以从应用程序上下文中获取bean:
ApplicationContext ctx = ...;
MyBean mb = ctx.getBean(MyBean.class);//getting by type
@Autowired)访问其他bean| 归档时间: |
|
| 查看次数: |
2557 次 |
| 最近记录: |