Java 自动装配在 Spring 中是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3153546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:54:37  来源:igfitidea点击:

How does autowiring work in Spring?

javaspringspring-mvcioc-containerautowired

提问by Blankman

I'm a little confused as to how the inversion of control(IoC) works in Spring.

对控制反转( IoC) 在Spring.

Say I have a service class called UserServiceImplthat implements UserServiceinterface.

假设我有一个名为UserServiceImpl实现UserService接口的服务类。

How would this be @Autowired?

这会@Autowired怎样?

And in my Controllers, how would I instantiatean instanceof this service?

而在我Controllers,我怎么会instantiateinstance这个服务的?

Would I just do the following?

我会做以下事情吗?

UserService userService = new UserServiceImpl();

采纳答案by Bozho

First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".

首先,也是最重要的——所有 Spring bean 都被管理——它们“存在于”一个容器中,称为“应用程序上下文”。

Second, each application has an entry point to that context. Web applications have a Servlet, JSFuses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.

其次,每个应用程序都有一个该上下文的入口点。Web 应用程序有一个 Servlet,JSF使用一个 el-resolver 等。此外,还有一个地方可以引导应用程序上下文和所有 bean - 自动装配。在 Web 应用程序中,这可以是启动侦听器。

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

自动装配是通过将一个 bean 的实例放入另一个 bean 实例中的所需字段来实现的。这两个类都应该是 bean,即它们应该被定义为存在于应用程序上下文中。

What is "living" in the application context? This means that the contextinstantiates the objects, not you. I.e. - you never make new UserServiceImpl()- the container finds each injection point and sets an instance there.

什么是应用程序上下文中的“生活”?这意味着上下文实例化对象,而不是您。即 - 你永远不会new UserServiceImpl()- 容器找到每个注入点并在那里设置一个实例。

In your controllers, you just have the following:

在您的控制器中,您只有以下内容:

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

A few notes:

一些注意事项:

  • In your applicationContext.xmlyou should enable the <context:component-scan>so that classes are scanned for the @Controller, @Service, etc. annotations.
  • The entry point for a Spring-MVC application is the DispatcherServlet, but it is hidden from you, and hence the direct interaction and bootstrapping of the application context happens behind the scene.
  • UserServiceImplshould also be defined as bean - either using <bean id=".." class="..">or using the @Serviceannotation. Since it will be the only implementor of UserService, it will be injected.
  • Apart from the @Autowiredannotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resourcecan also be used.
  • 在你的applicationContext.xml,你应该让<context:component-scan>这样的类被扫描了@Controller@Service等注释。
  • Spring-MVC 应用程序的入口点是 DispatcherServlet,但它对您隐藏,因此应用程序上下文的直接交互和引导发生在幕后。
  • UserServiceImpl也应该定义为 bean - 使用<bean id=".." class="..">或使用@Service注释。由于它将是 的唯一实现者UserService,因此将被注入。
  • 除了@Autowired注解之外,Spring 还可以使用 XML 可配置的自动装配。在这种情况下,所有名称或类型与现有 bean 匹配的字段都会自动注入 bean。事实上,这是自动装配的最初想法——在没有任何配置的情况下注入依赖项的字段。也可以使用其他注释,例如@Inject, @Resource

回答by Ben J

Depends on whether you want the annotations route or the bean XML definition route.

取决于您是想要注释路由还是 bean XML 定义路由。

Say you had the beans defined in your applicationContext.xml:

假设您在以下文件中定义了 bean applicationContext.xml

<beans ...>

    <bean id="userService" class="com.foo.UserServiceImpl"/>

    <bean id="fooController" class="com.foo.FooController"/>

</beans>

The autowiring happens when the application starts up. So, in fooController, which for arguments sake wants to use the UserServiceImplclass, you'd annotate it as follows:

自动装配发生在应用程序启动时。因此,在fooController,为了论证而想要使用UserServiceImpl该类,您可以按如下方式对其进行注释:

public class FooController {

    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than one UserServicebean, then you'll have to qualify which one it should use.

当它看到 时@Autowired,Spring 会寻找与 中的属性匹配的类applicationContext,并自动注入它。如果您有多个UserServicebean,那么您必须确定它应该使用哪一个。

If you do the following:

如果您执行以下操作:

UserService service = new UserServiceImpl();

It will not pick up the @Autowiredunless you set it yourself.

@Autowired除非您自己设置,否则它不会拾取。

回答by mohit bansal

@Autowiredis an annotation introduced in Spring 2.5, and it's used only for injection.

@Autowired是 Spring 2.5 引入的注解,仅用于注入。

For example:

例如:

class A {

    private int id;

    // With setter and getter method
}

class B {

    private String name;

    @Autowired // Here we are injecting instance of Class A into class B so that you can use 'a' for accessing A's instance variables and methods.
    A a;

    // With setter and getter method

    public void showDetail() {
        System.out.println("Value of id form A class" + a.getId(););
    }
}

回答by Jitender Chahar

You just need to annotate your service class UserServiceImplwith annotation:

您只需要使用注释来注释您的服务类UserServiceImpl

@Service("userService")

Spring container will take care of the life cycle of this class as it register as service.

Spring 容器将在该类注册为服务时负责该类的生命周期。

Then in your controller you can auto wire (instantiate) it and use its functionality:

然后在您的控制器中,您可以自动连接(实例化)它并使用其功能:

@Autowired
UserService userService;

回答by jeet singh parmar

How does @Autowiredwork internally?

@Autowired内部如何运作?

Example:

例子:

class EnglishGreeting {
   private Greeting greeting;
   //setter and getter
}

class Greeting {
   private String message;
   //setter and getter
}

.xml file it will look alike if not using @Autowired:

.xml 文件,如果不使用,它看起来很像@Autowired

<bean id="englishGreeting" class="com.bean.EnglishGreeting">
   <property name="greeting" ref="greeting"/>
</bean>

<bean id="greeting" class="com.bean.Greeting">
   <property name="message" value="Hello World"/>
</bean>

If you are using @Autowiredthen:

如果您正在使用,@Autowired则:

class EnglishGreeting {
   @Autowired //so automatically based on the name it will identify the bean and inject.
   private Greeting greeting;
   //setter and getter
}

.xml file it will look alike if not using @Autowired:

.xml 文件,如果不使用,它看起来很像@Autowired

<bean id="englishGreeting" class="com.bean.EnglishGreeting"></bean>

<bean id="greeting" class="com.bean.Greeting">
   <property name="message" value="Hello World"/>
</bean>

If still have some doubt then go through below live demo

如果仍有疑问,请通过下面的现场演示

How does @Autowired work internally ?

@Autowired 如何在内部工作?

回答by k13i

The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies. When you annotate class with appropriate annotation (e.g. @Service) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the newkeyword) in unit tests when you don't want to load the whole spring context.

控制反转的整个概念意味着您无需手动实例化对象并提供所有必要的依赖项。当您使用适当的注释(例如@Service)注释类时,Spring 将自动为您实例化对象。如果您不熟悉注释,也可以使用 XML 文件代替。但是,new当您不想加载整个 spring 上下文时,在单元测试中手动(使用关键字)实例化类并不是一个坏主意。

回答by AbdusSalam

Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:

Spring 依赖注入可帮助您从类中移除耦合。而不是像这样创建对象:

UserService userService = new UserServiceImpl();

You will be using this after introducing DI:

介绍 DI 后,您将使用它:

@Autowired
private UserService userService;

For achieving this you need to create a bean of your service in your ServiceConfigurationfile. After that you need to import that ServiceConfigurationclass to your WebApplicationConfigurationclass so that you can autowire that bean into your Controller like this:

为了实现这一点,您需要在您的ServiceConfiguration文件中创建一个服务 bean 。之后,您需要将该ServiceConfiguration类导入到您的WebApplicationConfiguration类中,以便您可以将该 bean 自动装配到您的控制器中,如下所示:

public class AccController {

    @Autowired
    private UserService userService;
} 

You can find a java configuration based POC here example.

您可以在示例中找到基于 Java 配置的 POC 。

回答by David Pham

Keep in mind that you must enable the @Autowiredannotation by adding element <context:annotation-config/>into the spring configuration file. This will register the AutowiredAnnotationBeanPostProcessorwhich takes care the processing of annotation.

请记住,您必须@Autowired通过<context:annotation-config/>在 spring 配置文件中添加元素来启用注释。这将注册AutowiredAnnotationBeanPostProcessor负责注解的处理。

And then you can autowire your service by using the field injection method.

然后您可以使用字段注入方法自动装配您的服务。

public class YourController{

 @Autowired
 private UserService userService; 

}

I found this from the post Spring @autowired annotation

我从Spring @autowired 注释中找到了这个

回答by Mak

There are 3 ways you can create an instance using @Autowired.

有 3 种方法可以使用@Autowired.

1. @Autowiredon Properties

1.@Autowired关于属性

The annotation can be used directly on properties, therefore eliminating the need for getters and setters:

注释可以直接用于属性,因此无需使用 getter 和 setter:

    @Component("userService")
    public class UserService {

        public String getName() {
            return "service name";
        }
    }

    @Component
    public class UserController {

        @Autowired
        UserService userService

    }

In the above example, Spring looks for and injects userServicewhen UserControlleris created.

在上面的示例中,SpringuserServiceUserController创建时查找并注入。

2. @Autowiredon Setters

2.@Autowired关于二传手

The @Autowiredannotation can be used on setter methods. In the below example, when the annotation is used on the setter method, the setter method is called with the instance of userServicewhen UserControlleris created:

@Autowired批注可在setter方法中使用。在下面的示例中,当在 setter 方法上使用注解时,setter 方法将使用创建的userServicewhen实例调用UserController

public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
            this.userService = userService;
    }
}

3. @Autowiredon Constructors

3.@Autowired关于构造函数

The @Autowiredannotation can also be used on constructors. In the below example, when the annotation is used on a constructor, an instance of userServiceis injected as an argument to the constructor when UserControlleris created:

@Autowired注释也可以在构造函数中使用。在下面的示例中,当在构造函数上使用注解userService时,UserController会在创建时将 的实例作为参数注入构造函数:

public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService= userService;
    }
}

回答by Pratik Gaurav

In simple words Autowiring, wiring links automatically, now comes the question who does this and which kind of wiring. Answer is: Container does this and Secondary type of wiring is supported, primitives need to be done manually.

简单地说,自动布线,自动布线,现在问题是谁做的,哪种布线。答案是:Container 执行此操作,并且支持辅助类型的接线,需要手动完成原语。

Question: How container know what type of wiring ?

问题:容器如何知道什么类型的接线?

Answer: We define it as byType,byName,constructor.

答:我们将其定义为 byType,byName,constructor。

Question: Is there are way we do not define type of autowiring ?

问题:有没有办法不定义自动装配的类型?

Answer: Yes, it's there by doing one annotation, @Autowired.

回答:是的,它是通过做一个注释来实现的,@Autowired。

Question: But how system know, I need to pick this type of secondary data ?

问题:但是系统怎么知道,我需要选择这种类型的辅助数据?

Answer: You will provide that data in you spring.xml file or by using sterotype annotations to your class so that container can themselves create the objects for you.

答:您将在 spring.xml 文件中或通过对类使用构造型注释来提供该数据,以便容器可以自己为您创建对象。