Spring Dependency injection for interfaces

好久不见. 提交于 2019-12-19 00:58:27

问题


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?


回答1:


You can do it like this:

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 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.

<beans ...>

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

</beans>



回答2:


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




回答3:


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

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



来源:https://stackoverflow.com/questions/13815139/spring-dependency-injection-for-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!