接口的Spring依赖注入

时间:2012-12-11 06:57:49

标签: java spring interface dependency-injection

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

我的意思是,例如,我有一个变量

@Autowired
ClassA someObject;

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

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

4 个答案:

答案 0 :(得分:23)

你可以这样做:

界面:

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();
       }

}

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

<beans ...>

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

</beans>

答案 1 :(得分:1)

您必须在applicationContext.xml文件中指定要创建对象的类的类型,或者可以使用@Component@Service或{{1}中的任何一个直接注释该类如果您使用的是最新版本的Spring。在web.xml中,如果使用基于xml的配置,则必须将xml文件的路径指定为servlet的上下文参数。

答案 2 :(得分:0)

是的,您必须提供一个context.xml文件,您可以在其中指定实例。将它提供给ApplicationContext,它将为您自动装配所有字段。

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

答案 3 :(得分:0)

最佳做法

@RestController
@RequestMapping("/order")
public class OrderController {
    private final IOrderProducer _IOrderProducer;

    public OrderController(IOrderProducer iorderProducer) {
        this._IOrderProducer = iorderProducer;
    }

    @GetMapping("/OrderService")
    void get() {
        _IOrderProducer.CreateOrderProducer("This is a Producer");
    }
}

界面

@Service
public interface IOrderProducer {
    void CreateOrderProducer(String message);
}

实施

public class OrderProducer implements  IOrderProducer{
    private KafkaTemplate<String, String> _template;

    public OrderProducer(KafkaTemplate<String, String> template) {
        this._template = template;
    }

    public void CreateOrderProducer(String message){
        this._template.send("Topic1", message);
    }
}

您需要在春季启动时包含Project Lombok依赖项

等级implementation 'org.projectlombok:lombok'

相关问题