Well I’ve been watching some tutorials about Spring dependency injection as well as MVC, but I still seem to not understand how we can instantiate classes specifically?
I mean if for instance I have a variable
@Autowired
ClassA someObject;
How can I make spring create someObject as an Instance of ClassB which would extend ClassA? like someObject = new ClassB();
I don’t really understand how it works in spring, does the ContextLoaderListener do it automatically or do we have to create some kind of configuration class where we specify exactly what spring should instantiate those classes to? (In this case I haven’t seen that anywhere in the tutorials) If yes, then how do we specify and how does it look like? And how do we configure it to work in web.xml, etc?
You can do it like this:
Interface:
Implementation:
Client:
Now you have your interface defined, written an implementation and marked it as a component – docs here. Now only thing left is to tell spring where to find components so they can be used for autowiring.