接口的Spring依赖注入 [英] Spring Dependency injection for interfaces

查看:160
本文介绍了接口的Spring依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在观看有关Spring依赖注入以及MVC的一些教程,但我似乎还不明白我们如何专门实例化类?

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意思是,例如我有一个变量

I mean if for instance I have a variable

@Autowired
ClassA someObject;

如何使spring创建someObject作为ClassB的实例,它将扩展ClassA?比如someObject = new ClassB();

How can I make spring create someObject as an Instance of ClassB which would extend ClassA? like someObject = new ClassB();

我真的不明白它在春天是如何工作的,ContextLoaderListener是自动完成还是我们必须创建某种类型的配置类,我们确切地指定spring应该将那些类实例化为什么? (在这种情况下,我没有在教程中的任何地方看到过)如果是,那么我们如何指定它们是什么样的?我们如何配置它在web.xml等工作?

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?

推荐答案

你可以这样做:

接口:

package org.better.place

public interface SuperDuperInterface{
    public void saveWorld();
}

实施:

package org.better.place

import org.springframework.stereotype

@Component
public class SuperDuperClass implements SuperDuperInterface{
     public void saveWorld(){
          System.out.println("Done");
     }
}

客户:

package org.better.place

import org.springframework.beans.factory.annotation.Autowire;

public class SuperDuperService{
       @Autowire
       private SuperDuperInterface superDuper;


       public void doIt(){
           superDuper.saveWorld();
       }

}

现在你已经定义了你的界面,编写了一个实现并将其标记为一个组件 - 这里的文档。现在唯一剩下的就是告诉spring在哪里找到组件,这样它们就可以用于自动装配。

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>

这篇关于接口的Spring依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆