java - 在 Spring Boot 应用程序中实例化 @Service @Transactional 类的多个 bean
问题描述
我对 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 制作为 的任何线索,该 bean@Service
@Transactional
将从资源中调用。有人可以帮忙吗?谢谢。
解决方案
您不需要在类上声明 @Service,因为当您没有 @Bean 配置时,它用于自动检测 bean。
对于事务,您可以从类中省略@Transactional,并通过在添加@Bean 声明的同时手动创建代理类来添加事务来实现相同的功能。参考以下:
推荐阅读
- sql-server - 防止在另一个 SQL Server 中附加我的本地数据库并防止访问我的数据?
- java - 用户长按时更改android上的任何按钮
- javascript - 在 nodejs express 中处理 Unhandling Promise Rejection
- groovy - 如何在JSR223的Groovy类中使用JMeter的内部方法(vars.get()等)
- react-native - 升级到 react-native 0.59.x 后还可以使用 react-navigation 2.x 吗?
- coldfusion - 在两个页面之间丢失会话变量
- firebase - 是否可以通过 CLI 添加自定义声明?
- angularjs - 隧道服务器离线:请求失败,状态码 502,当我运行 gulp serve 时重试 1 秒
- excel - 如果嵌套 if 语句中的一个或两个单元格为空,如何在一个单元格中返回 0?
- pandas - 与每列的中位数进行比较