问题

关于inversion of control(IoC)如何在Spring中​​工作,我有点困惑。
假设我有一个名为UserServiceImpl的服务类,它实现了UserService接口。
怎么会这个be@Autowired

在myControllers中,Iinstantiateaninstance将如何提供这项服务?

我会做以下吗?

UserService userService = new UserServiceImpl();

#1 热门回答(601 赞)

首先,也是最重要的 - 所有Spring bean都是托管的 - 它们"活在"容器内,称为"应用程序上下文"。

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

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

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

在你的控制器中,你只需拥有以下内容:

@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);

    }
}

几点说明:

  • 在applicationContext.xml中,你应该启用<context:component-scan>,以便扫描类以获取@Controller,@ Service等注释。
  • Spring-MVC应用程序的入口点是DispatcherServlet,但它对你是隐藏的,因此应用程序上下文的直接交互和引导发生在场景后面。
  • UserServiceImpl也应定义为bean - 使用<bean id =".."class ="..">或使用@Service注释。由于它将是UserService的唯一实现者,因此将被注入。
  • 除了@Autowired注释之外,Spring还可以使用XML可配置的自动装配。在这种情况下,所有具有与现有bean匹配的名称或类型的字段都会自动获取注入的bean。实际上,这是自动装配的最初想法 - 在没有任何配置的情况下为字段注入依赖关系。也可以使用@ Inject,@ Resource等其他注释。

#2 热门回答(59 赞)

取决于你是否使用了注释路由或bean XML定义路由。

假设你在yourapplicationContext.xml中定义了bean:

<beans ...>

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

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

</beans>

应用程序启动时会发生自动装配。所以,在fooController中,为了论证,想要使用UserServiceImplclass,你需要注释如下:

public class FooController {

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

    // rest of class goes here
}

当它看到3777797876时,Spring将查找与applicationContext中的属性匹配的类,并自动注入它。如果你有多个UserService bean,那么你必须确定应该使用哪一个。

如果你执行以下操作:

UserService service = new UserServiceImpl();

除非你自己设置,否则它不会接收@Autowired。


#3 热门回答(18 赞)

@Autowired是Spring 2.5中引入的注释,它仅用于注入。

例如:

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

原文链接