gpt4 book ai didi

java - 在 Spring 中使用 getBean 获取 bean

转载 作者:行者123 更新时间:2023-11-30 01:45:38 24 4
gpt4 key购买 nike

这个问题听起来可能很蹩脚,但我有一个疑问,所以我想把它弄清楚。我正在阅读 Ashish Sarin 的 Spring Framework 入门,其中有一个简单的代码可以获取固定存款服务类类型的 spring bean

package sample.spring.chapter06.bankapp;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import sample.spring.chapter06.bankapp.domain.FixedDepositDetails;
import sample.spring.chapter06.bankapp.service.FixedDepositService;

public class BankApp {
public static void main(String args[]) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:META-INF/spring/applicationContext.xml");

FixedDepositService fixedDepositService = context
.getBean(FixedDepositService.class);
fixedDepositService.createFixedDeposit(new FixedDepositDetails(1, 0,
12, "someemail@somedomain.com"));
fixedDepositService.createFixedDeposit(new FixedDepositDetails(1, 1000,
12, "someemail@somedomain.com"));
}
}

现在,FixedDepositService 是一个接口(interface),而不是一个具体的类。它是由另一个名为FixedDepositServiceImpl 的类实现的,如下所示

....
@Service(value = "fixedDepositService")
public class FixedDepositServiceImpl implements FixedDepositService {
....
}

我的问题是,这段代码是如何工作的?难道BankApp类不应该获取FixedDepositServiceImpl类的bean而不是FixedDepositService类吗?因为FixedDepositService只是一个接口(interface),不包含任何方法定义,而FixedDepositServiceImpl是实际实现它的类,并在其中定义了所有逻辑?

最佳答案

直接你可以使用getClass().getName()来查看它是哪个类对象

FixedDepositService service = (FixedDepositService) context.getBean("fixedDepositService");

System.out.println(service.getClass().getName()); //FixedDepositServiceImpl

关于java - 在 Spring 中使用 getBean 获取 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108101/

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