Spring Enabling Dependencies for Interfaces

Well, I looked at a few tutorials regarding Spring dependency injection as well as MVC, but I still don't seem to understand how we can specifically create classes?

I mean, if, for example, I have a variable

@Autowired ClassA someObject; 

How can I make Spring create someObject as an instance of class B that extends ClassA? for example someObject = new ClassB ();

I really don’t understand how this works in spring, does ContextLoaderListener do this automatically or do we need to create some kind of configuration class, where we determine exactly what Spring should instantiate these classes? (In this case, I did not see anything in the textbooks). If so, how do we indicate and what does it look like? And how do we configure it to work in web.xml, etc.

+8
source share
4 answers

You can do it as follows:

Interface:

 package org.better.place public interface SuperDuperInterface{ public void saveWorld(); } 

Implementation:

 package org.better.place import org.springframework.stereotype @Component public class SuperDuperClass implements SuperDuperInterface{ public void saveWorld(){ System.out.println("Done"); } } 

Client:

 package org.better.place import org.springframework.beans.factory.annotation.Autowire; public class SuperDuperService{ @Autowire private SuperDuperInterface superDuper; public void doIt(){ superDuper.saveWorld(); } } 

Now you have defined your interface, written an implementation, and marked it as a component - docs here . Now all that remains is to tell spring where to find the components so that they can be used for auto-tuning.

 <beans ...> <context:component-scan base-package="org.better.place"/> </beans> 
+23
source

You must specify the type of class you want to create the object in the applicationContext.xml file, or you can directly annotate this class using any @Component , @Service or @Repository if you are using the latest version of Spring. In web.xml, you need to specify the path to the xml files as context-param for the servlet if you are using xml-based configuration.

+1
source

Yes, you must provide a context.xml file in which you specify instances. Give it to ApplicationContext, and it will autwire all the fields for you.

http://alvinalexander.com/blog/post/java/load-spring-application-context-file-java-swing-application

0
source

You can use the wrapping of your interface and implement it using the @Component class, or perhaps use the Proxy Design Pattern.

0
source

All Articles