【发布时间】:2021-05-30 14:53:44
【问题描述】:
我对 Spring Boot 比较陌生。我正在开发一个 Spring Boot 应用程序,我需要为同一个 POJO 注入两个不同的 bean。
截至目前,我的服务类如下:
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
private final StudentHelper studentHelper;
private final Validator validator;
public StudentServiceImpl(
StudentHelper studentHelper,
Validator validator) {
this.studentHelper = studentHelper;
this.validator = validator;
}
@Override
public List<Student> generateReport(String courseId) {
...
if(validator != null) {
validator.validate(courseId);
}
...
}
现在,我想为同一个 POJO 实例化两个不同的 bean:StudentServiceImpl,一个带有正确的验证器,另一个带有一个 null 的验证器。其实StudentServiceImpl
正在从两个流程中使用:一个是从需要验证器的资源调用,另一个是从不需要验证器的调度程序调用。
在这方面,我已经看过多个示例,但我不知道如何制作两个 bean,其中一个用作上述事务服务类,另一个用作简单组件.
基本上,我可以弄清楚,我必须编写如下配置:
@Configuration
public class StudentServiceConfig {
@Bean //THIS BEAN IS TO BE USED AS TRANSACTIONAL SERVICE AS MENTIONED ABOVE
public StudentServiceImpl studentServiceOne(StudentHelper helper, Validator validator) {
return new StudentServiceImpl(helper, validator);
}
@Bean
public StudentServiceImpl studentServiceTwo(StudentHelper helper) {
return new StudentServiceImpl(helper, null);
}
}
在这里,正如我上面提到的,我没有得到任何关于如何将 bean 之一作为@Service @Transactional 的线索,这将从资源中调用。有人可以帮忙吗?谢谢。
【问题讨论】:
标签: java spring spring-boot spring-annotations