java - 静态方法与原型 bean
问题描述
我有实用方法,它将字符串作为输入参数并给我一个与输入相对应的对象。我需要从 Spring 引导请求映射方法中调用此实用程序方法。
现在我的问题是以下两种方法的优缺点是什么?
- 将实用程序方法设为静态并调用它。
- 将方法制作为原型 bean 并调用该 bean。
方法 1 的示例代码:
**//SourceSystem can change at runtime**
public static FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
方法 2 的示例代码:
@Bean
@Scope(value = "prototype")
**//SourceSystem can change at runtime**
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
PS:从其他帖子收集的样本。
解决方案
如果您已经使用 Spring,则选择单例(每个 Spring 容器实例一个 bean 对象)bean(这是默认范围),如果您的静态方法没有任何共享状态,则可以。如果您选择原型,那么 Spring 容器将为每次getBean()
调用返回 bean 对象的新实例。并将该 bean 注入需要调用该方法的对象。这种方法也比静态方法对单元测试更友好,因为您可以在测试应用程序上下文中使用这种方法提供 bean 的测试实现。在静态方法的情况下,您将需要 PowerMock 或其他 3rd 方库来模拟棒方法以进行单元测试。
更新
在你的情况下应该有新豆
@Service
public MyReportBeanFactory {
@Autowired
private Dao dao;
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
}
然后您需要将此工厂 bean 注入您要调用的类中fixedLengthReport()
推荐阅读
- node.js - 计算 mongodb 中的不同值文档
- python - 试图从文本数据中提取数字,但 re.findall() 没有找到任何东西
- wpf - WPF 从 MainWindow 类访问页面控件
- android - org.gradle.tooling.BuildException:无效的代码长度设置 dlib
- javascript - 未捕获的类型错误:无法读取未定义的属性“行”在角度 js 中不起作用
- c# - C# 模拟 IHttpclient 和 CreateClient
- wcf - 发送大于 100mb 的消息时 WCF 错误 400 错误请求
- java - HibernateException:无法访问 lob 流
- asp.net-core - 如何在 asp.net 核心启动中保存信息以在应用程序中可用
- ajax - POST 请求在 chrome 中没有得到服务器的响应,但在邮递员中工作