9

好吧,我一直在看一些关于 Spring 依赖注入和 MVC 的教程,但我似乎仍然不明白我们如何具体实例化类?

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

@Autowired
ClassA someObject;

我怎样才能让spring创建someObject作为ClassB的一个实例来扩展ClassA?像 someObject = new ClassB();

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

4

4 回答 4

32

你可以这样做:

界面:

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 在哪里可以找到组件,以便它们可以用于自动装配。

<beans ...>

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

</beans>
于 2012-12-11T07:11:24.087 回答
1

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

于 2012-12-11T07:05:48.067 回答
0

是的,您必须提供指定实例的 context.xml 文件。把它交给 ApplicationContext ,它会为你自动装配所有字段。

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

于 2012-12-11T07:01:14.853 回答
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);
    }
}

您需要在 Spring Boot 中包含 Project Lombok 依赖项

摇篮implementation 'org.projectlombok:lombok'

于 2020-07-11T13:06:43.207 回答