[英]Spring - injection java.util classes
I'm working on java.util classes injection, with Spring.我正在使用 Spring 进行 java.util 类注入。
I wonder, do you register your bean classes like Scanner
or Random
in Spring's context?我想知道,您是否在 Spring 的上下文中注册了像
Scanner
或Random
这样的 bean 类?
I guess this decision depends on how often you will use it, right?我想这个决定取决于你使用它的频率,对吗?
What is the number of usages when I should consider returning bean instead of creating a new object?当我应该考虑返回 bean 而不是创建新对象时,使用次数是多少?
Do you want multiple beans to share a single source of random numbers?您是否希望多个 bean 共享一个随机数源? If so, then the beans needs to be injected with a random number generator bean.
如果是这样,则需要使用随机数生成器 bean 注入 bean。
It is however recommended to use ThreadLocalRandom
in a multi-threaded program (for better performance), and it doesn't hurt in a single-threaded program, so general recommendation is to use that, which means Random
should never be a Spring bean.然而,建议在多线程程序中使用
ThreadLocalRandom
(以获得更好的性能),并且它在单线程程序中不会受到伤害,所以一般建议使用它,这意味着Random
永远不应该是 Spring bean。
However, if you need to unit test code, using a seeded random number sequence, then code needs to be injected with a random number bean that can be mocked.但是,如果您需要使用种子随机数序列对代码进行单元测试,则需要将代码注入可以模拟的随机数 bean。
Note however, that such random number bean is not the Random
class itself, but a wrapper/helper bean.但是请注意,这种随机数 bean 不是
Random
类本身,而是一个包装器/帮助器 bean。
Do you want multiple beans to share a single Scanner
?你想让多个 bean 共享一个
Scanner
吗?
That question really only makes sense in a command-line program, reading System.in
, in which case answer is yes.这个问题只有在命令行程序中才有意义,阅读
System.in
,在这种情况下答案是肯定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.