如何通过手动bean 进行依赖注入?
How can dependency injection by manual bean?
您好,我想知道通过手动注册 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... !!
}
谢谢。
您可以为使用 @Bean(name="customModelMapper")
创建的 ModelMapper bean 命名,然后使用 @Autowired
和 @Qualifier("customModelMapper")
注入它。所以你的服务看起来像这样:
@Service
public class Service {
@Autowired
@Qualifier("customModelMapper")
private ModelMapper mapper;
}
您好,我想知道通过手动注册 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... !!
}
谢谢。
您可以为使用 @Bean(name="customModelMapper")
创建的 ModelMapper bean 命名,然后使用 @Autowired
和 @Qualifier("customModelMapper")
注入它。所以你的服务看起来像这样:
@Service
public class Service {
@Autowired
@Qualifier("customModelMapper")
private ModelMapper mapper;
}