3 ms·
Having used Spring for a year or so now, I'm curious what people think of singletons in Spring? Most of the problems noted in the OP (inability to use interface
by msluyter 13y ago
Having used Spring for a year or so now, I'm curious what people think of singletons in Spring? Most of the problems noted in the OP (inability to use interfaces, unable to mock, tight coupling, etc...) aren't really problems that I've noticed. For example, if you're autowiring a typical spring bean, as in:
@Autowired
private Blah blah;
You can actually autowire an interface here. Similarly, it's pretty easy to mock these or swap them out in tests. Parallelization is usually handled by not storing private state in a singleton bean.
I'm no Spring expert, so I'm not sure what I may be missing, but most of these concerns appear to be less problematic than many suggest.[1]
[1] Nothing is perfect, of course. I have noticed problems with spring singletons where a test would basically screw up the application context, causing subsequent tests to fail. This caused some hair pulling until I learned about @DirtiesContext.
- UK-AL 13y agoSpring does it right. This is a IoC container btw, and not unique to spring. This isn't a singleton, but a single instance of a object. You can change the lifetime of an object, by changing a setting in the IoC container. From ApplicationLifetime To SessionLifetime quite easily. That solves the biggest problem of the singleton, which if you ever DO need more than one, it requires a refactoring. I hate singletons, and I'm a iOS developer. So i'm continually mad about misuse of singletons(Working on legacy code).
- masklinn 13y agoThat's not a singleton, that's just injecting the same instance everywhere.
- taeric 13y agoHow is that not a singleton? I can see the argument that dependency injection is better than a factory method. Especially considering the memory model, but I thought this was still a singleton.
- masklinn 13y ago> How is that not a singleton? The way it is normally used, a singleton is a self-managing, globally accessible, single-instanced object (lazy or not). Just having a single instance does not a singleton make.
- taeric 13y agoSo the complaint is against the implementation detail of a singleton? Because, just having a single instance is the crux of the benefit for that pattern.
- brown9-2 13y agoSpring makes the discussion confusing because it refers to "single instances of a class" as "singleton" scope. What is being debated here is when a class intentionally restricts how many instances of itself can be instantiated. That is the true "Singleton pattern" - a class that combines two concerns, 1) the behavior of the class and 2) the instantiation pattern of the class.