如何从@Bean return 一个与其他 bean 有依赖关系的 bean

How to return from @Bean a bean that has dependencies to other beans

我有一个带注释的@Configuration class,它有带@Bean 带注释的方法。其中大多数 return 只是没有 DI 依赖项的新实例,例如:

@Bean
public UserService getUserService() {
    return new InMemoryUserService();
}

但是有些bean需要构造函数注入,例如

@Bean
public BookingService getBookingService() {
    return new InMemoryBookingServiceImpl(???); // i need to inject UserService to constructor
}

我该怎么做?

只需将您需要的 bean 作为参数传递给该方法即可。

@Bean
public UserService getUserService() {
    return new InMemoryUserService();
}

@Bean
public BookingService getBookingService(UserService userServ) {
    return new InMemoryBookingServiceImpl(userServ); 
}

此处,当 Spring 到达 getBookingService 时,它将发现它需要一个类型为 UserService 的 bean,并将在上下文中寻找一个。

docs

所有依赖项注入规则均适用。如果没有找到该类型的 bean,则会抛出异常,或者如果找到多个该类型的 bean,则必须使用 @Qualifier 指定所需 bean 的名称,或标记其中一个豆 @Primary

另一种选择是直接使用生成依赖bean 的方法:

@Bean
public UserService getUserService() {
    return new InMemoryUserService();
}

@Bean
public BookingService getBookingService() {
    return new InMemoryBookingServiceImpl(getUserService()); 
}