Spring Bean Names
To create a bean, spring needs some kind of identifier that tells it which class should be instantiated. It's a piece of cake when it comes to instantiating concrete classes or interfaces, for which only one implementation exists. But what about multiple implementations of an interface? How does Spring know which implementation to pick?
It turns out, that we can leverage on Springs internal mechanism to associate beans with a name. After all, spring needs an identifier for every bean that it encounters when starting up in order to create it. Or how does Spring know what to do when it encounters @Autowired Foo field
?
Depending on how we declare Beans, spring comes up with a name to identify it. If we declare a bean method spring uses the methode name, where if we annotate a class with @Component
or @Service
spring uses the class name as an identifier.
How do we use this?
Let's illustrate this with a simple example. We have an interface Publisher
for which we have two implementations.
FacebookPublisher
TwitterPublisher
Whenever we want to use the Publisher-Interface Spring needs to know which implementation to instantate. We do this by naming our field accordingly. If Facebook is our platform of choice, we declare our publisher like this:
@Autowired Publisher facebookPublisher
Thats a nice and quick way of telling Spring what we want to wire together. But using this method has its flaws.
-
Your code now does no longer speak a functional language but reflects concrete technological choices to fullfill requirements. After all, what we want to do is publish and our code should not care whether we want to publish Images to Facebook or some text to Twitter.
-
Also, changing the used implementation of our Publisher now involves a bit more handcraft since we now have to rename our field from
facebookPublisher
totwitterPublisher
for instance. (I know, a no-brainer with todays IDEs, but still, someone's got to do the work)
So, personally, I would go with the above when writing a simple POC. To cleanly controll bean instantiation I would prefer one of the following ways instead.
@Qualifier
which lets you define custom identifier for beans@Profiles
control what set of beans Spring should take into account, discarding others completely