【问题标题】:How can dependency injection by manual bean?如何通过手动bean进行依赖注入?
【发布时间】:2021-03-12 04:33:16
【问题描述】:

您好,我想通过手动注册 bean 而非自动 bean 来了解依赖注入。

这是自动注册 bean

@Service
public class Service {
 @Autowired
 private ModelMapper mapper;
}

这很简单,但我想知道我进行配置的注入

例如)..

@Configuration
public class ModelMapperConfig {

  @Bean
  public ModelMapper modelMapper() {
    ModelMapper modelMapper = new ModelMapper();
    modelMapper
        .getConfiguration()
        .setMatchingStrategy(MatchingStrategies.STRICT);

    return modelMapper;
  }
}

@Service
public class Service {
 
 // i want dependency injection... !!
}

谢谢。

【问题讨论】:

  • 我想通过 ModelMapperConfig 使用 ModelMapper。

标签: java spring dependency-injection dependencies


【解决方案1】:

您可以使用@Bean(name="customModelMapper") 为您创建的ModelMapper bean 命名,然后使用@Autowired@Qualifier("customModelMapper") 注入它。所以你的服务看起来像这样:

@Service
public class Service {
 @Autowired
 @Qualifier("customModelMapper")
 private ModelMapper mapper;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2014-06-28
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多