【问题标题】:Create an Object in Spring with annotations (Inject, Autowired) or with getBean在 Spring 中使用注解(注入、自动装配)或使用 getBean 创建对象
【发布时间】:2015-01-24 06:04:49
【问题描述】:

我尝试在春季了解 DI。我应该在哪里使用带有 context.getBean 的对象以及在哪里使用 @inject 注释?

public class App {
    public static void main(String[] args) {
        new Controller().iniController();

    }
}

public class Controller {

    public void iniController() {       

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/beans/beans.xml");
        Address address = context.getBean("address", Address.class);
        Person person = context.getBean("person", Person.class);
        Employee employee = context.getBean("employee", Employee.class);

        address.setCity("my city");
        person.setName("my name");

        System.out.println(employee);

        context.close();
    }

}

使用 context.getBean 方法获取地址、人员和员工对象是否正确?


@Component
public class Employee {

    @Inject
    private Person person;
    @Inject
    private Address address;

    @Override
    public String toString() {
        return "Employee: "+ person.getName() +" from "+ address.getCity();
    }
}

这里我用 Inject 得到了 person 和 address 对象,我也可以用 getBean 方法得到这些吗?


@Component
public class Address {

    private String city;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

@Component
public class Person {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">


    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.model"></context:component-scan>
</beans>

【问题讨论】:

  • 首先:看一下Spring Boot。它为您处理大部分样板配置。您几乎不需要明确使用getBean;我想我从来没有真正的代码。

标签: java spring dependency-injection annotations inject


【解决方案1】:

你应该总是更喜欢依赖注入,而不是 getBean,或者我应该说完全避免使用 getBean..

依赖注入在关联松散耦合的组件以及配置这些组件方面非常有效。特别是如果组件之间的关联贯穿组件的整个生命周期。

更具体地说,依赖注入在这些情况下是有效的:

  1. 您需要将配置数据注入一个或多个组件。
  2. 您需要将相同的依赖项注入到多个组件中。你
  3. 您需要注入相同依赖项的不同实现。你
  4. 您需要在不同的配置中注入相同的实现。
  5. 您需要容器提供的一些服务。

定义 DI 可帮助您轻松更改底层实现,而无需真正担心使用此实现的人..

如果这一切仍然让你感到困惑,你可以在谷歌上找到几十个使用 DI 的理由

【讨论】:

  • 感谢您的精彩回复。理论上我知道,但是在实践中如何解决这样简单的例子。
猜你喜欢
  • 2010-11-12
  • 2014-08-24
  • 1970-01-01
  • 2013-05-03
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多