【发布时间】:2016-09-23 12:30:01
【问题描述】:
我有一个@Configuration 注释类,它有@Bean 注释方法。它们中的大多数只返回没有 DI 依赖关系的新实例,例如:
@Bean
public UserService getUserService() {
return new InMemoryUserService();
}
但有些bean需要构造函数注入,例如
@Bean
public BookingService getBookingService() {
return new InMemoryBookingServiceImpl(???); // i need to inject UserService to constructor
}
我该怎么做?
【问题讨论】:
-
为什么需要显式创建 InMemoryBookingServiceImpl 的实例?可以注释为@Component吗?
-
用
@Component注释InMemoryBookingServiceImpl类,同时将依赖项自动装配到其中,会不会更容易创建bean?