Spring注入java.util类:Scanner/Random何时注册为Spring Bean
Should We Register java.util Classes Like Scanner/Random as Spring Beans?
Great question—this is a common point of confusion when working with Spring and standard Java utility classes. Let’s break it down based on the specific class and actual usage scenarios, rather than just a strict "usage count" rule.
First, Let’s Analyze the Two Classes’ Characteristics
Scanner: This class is stateful—it maintains internal state tied to the input stream it’s reading from. If you’re using it to read fromSystem.in(standard input), sharing a single instance is critical: multipleScannerinstances pointing toSystem.incan cause unexpected behavior (like partial reads or input being consumed by the wrong instance).Random: This class is thread-safe, and creating a new instance has very low overhead. However, reusing a single instance is perfectly safe and consistent—you’ll just get a continuous sequence of random numbers, which is usually what you want.
When to Register as a Spring Bean?
For Scanner
- Always register as a singleton bean if you’re using
System.in: Even if you only use it once, having a single shared instance prevents input stream conflicts. You can define it like this:@Bean public Scanner systemInScanner() { return new Scanner(System.in); } - Never reuse a
Scannerfor different input streams: If you’re reading from files or custom streams, create a newScannerinstance each time—reusing one tied to a closed stream will cause errors.
For Random
- Register as a bean if you want consistent, centralized randomness: There’s no harm in making it a singleton, even if you only use it a few times. It keeps your dependency injection pattern consistent, and you can easily configure a seed if needed:
@Bean public Random random() { return new Random(); // Or pass a fixed seed for testing } - It’s okay to
new Random()locally if needed: If a component only needs random numbers in one method and has no need to share the instance, creating it on the fly is totally fine—no need to overcomplicate with a bean.
What About "Usage Count"?
The decision isn’t really about a specific number of uses. Instead, ask yourself:
- Is this instance shared across multiple components? If yes, register it as a bean.
- Does reusing it prevent bugs or inconsistencies? (Like with
ScannerandSystem.in) If yes, register it regardless of usage count. - Is creating a new instance costly or risky? For
Random, creation is cheap, but for heavier objects, reusing makes more sense.
At the end of the day, Spring’s dependency injection is about managing reusable, shared resources—if the utility class fits that bill, go with a bean. If it’s a one-off, local use, new is perfectly acceptable.
内容的提问来源于stack exchange,提问作者minizibi
相关产品推荐
相关产品推荐

