gpt4 book ai didi

java - 使用注释(Inject、Autowired)或使用 getBean 在 Spring 中创建对象

转载 作者:太空宇宙 更新时间:2023-11-04 14:21:29 24 4
gpt4 key购买 nike

我尝试在 Spring 中理解 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>

最佳答案

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

依赖注入(inject)对于关联松散耦合的组件以及配置这些组件非常有效。特别是如果组件之间的关联在组件的整个生命周期中持续存在。

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

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

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

如果这一切仍然让您感到困惑,您可以找到许多在 Google 上使用 DI 的理由

关于java - 使用注释(Inject、Autowired)或使用 getBean 在 Spring 中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com