Java Spring:getBean方法做什么?
我正在读以下文章: 我在那里找到了以下代码片段:Java Spring:getBean方法做什么?,java,spring,Java,Spring,我正在读以下文章: 我在那里找到了以下代码片段: package com.concretepage; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.concretepage.bean.Company; import com.concretepage.bean.Employee; @Configur
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.concretepage.bean.Company;
import com.concretepage.bean.Employee;
@Configuration
public class AppConfig {
@Bean
public Company getCompany() {
Company company = new Company();
company.setCompName("ABCD Ltd");
company.setLocation("Varanasi");
return company;
}
@Bean
public Employee getEmployee() {
return new Employee();
}
}
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.bean.Employee;
public class SpringDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
Employee employee = ctx.getBean(Employee.class);
System.out.println("Company Name:"+ employee.getCompany().getCompName());
System.out.println("Location:"+ employee.getCompany().getLocation());
ctx.close();
}
}
我想得到一个关于这条线的解释:
Employee employee = ctx.getBean(Employee.class);
“ctx”获取AppConfig类作为参数。AppConfig类包括两个方法getCompany和getEmployee。我不明白的是,如果我们有返回新“Employee”对象的方法“getEmployee”,为什么我们必须使用“ctx.getBean(Employee.class)”来做同样的事情
另外,在方法“getCompany”和“getEmployee”上使用注释“@Bean”有什么好处 Spring的ApplicationContext使用
@Bean
注释创建返回的Bean。默认情况下,只创建一个实例。豆子是单子
使用Employee=ctx.getBean(Employee.class)代码>每次调用时都返回相同的对象
因此,要回答您的问题:
如果我们有返回新“Employee”对象的方法“getEmployee”,为什么我们必须使用“ctx.getBean(Employee.class)”?
因为这就是Spring的应用程序上下文初始化bean的方式。它运行getEmployee()
方法并创建一个Bean
在方法“getCompany”和“getEmployee”上使用注释“@Bean”有什么好处?
如果不使用@Bean
Spring不知道您想要一个Bean
是的。。阅读一些Spring文档有很大的帮助。关于使用@Bean的好处:看看它:
D.I.(依赖注入)概念是您首先需要了解的,然后您将能够看到如何使用/注入这些@Bean