简体   繁体   中英

Spring - injection java.util classes

I'm working on java.util classes injection, with Spring.

I wonder, do you register your bean classes like Scanner or Random in Spring's context?

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?

Do you want multiple beans to share a single source of random numbers? If so, then the beans needs to be injected with a random number generator 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.

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.

Note however, that such random number bean is not the Random class itself, but a wrapper/helper bean.


Do you want multiple beans to share a single Scanner ?

That question really only makes sense in a command-line program, reading System.in , in which case answer is yes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM