gpt4 book ai didi

java - ClassCastException - 客户和客户服务位于加载程序应用程序的未命名模块中?

转载 作者:行者123 更新时间:2023-12-01 21:40:01 25 4
gpt4 key购买 nike

我试图在我的主应用程序中调用我的客户 Bean 来测试我的 Bean 设置是否正确(我可以看到它们正在创建),但出现以下错误:

Exception in thread "main" java.lang.ClassCastException: class com.r00107892.bank.domain.Customer cannot be cast to class com.r00107892.bank.services.CustomerService (com.r00107892.bank.domain.Customer and com.r00107892.bank.services.CustomerService are in unnamed module of loader 'app') at com.r00107892.bank.MainApp.main(MainApp.java:24)

我检查了我的 Customer.java、CustomerDAO.java、CustomerDAOImpl.java、CustomerService.java、CustomerServiceImpl.java、我的 mainApp 和我的 BeanConfig.java,但找不到问题。

我更改了 BeanConfig,使其不再显式将 Customer 命名为 Bean 并使用 ComponentScan。

主应用

@Configuration
public class MainApp {

public static void main(String[] args) {
AnnotationConfigApplicationContext context= new
AnnotationConfigApplicationContext (BeanConfig.class);

System.out.println("Bean names: " + Arrays.toString(context.getBeanNamesForType(BeanConfig.class)));

CustomerService customerService = (CustomerService) context.getBean("customer");

System.out.println(customerService.getCustomerByAccountNumber('1'));

context.close();
}
}

客户.java

@Component
public class Customer{
public String name;
public int account;


public Customer() {

}

public Customer(int account, String name){

}

public String getName() {
return name;

}

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

public int getAccount() {
return account;
}

public void setAccount(int account) {
this.account = account;
}

public void myDetails() {
System.out.println("My name is "+ this.name);
System.out.println("My name is" + this.account);
}

public String toString(String name, int account) {
String sentence = name + " " + account;
return sentence;

}

客户服务

@Service
public interface CustomerService {

Customer getCustomerByAccountNumber(int accountNumber);

}

客户服务Impl

public class CustomerServiceImpl implements CustomerService {

@Autowired
CustomerDAO customerDao;


public Customer getCustomerByAccountNumber(int accountNumber) {
return customerDao.findById(accountNumber);
}

我希望看到 1 号帐户的客户名称(已在数据库中)被打印出来。

最佳答案

应该是:

CustomerService customerService = (CustomerService) context.getBean("customerService");

您没有为 bean 指定名称,因此默认情况下它将采用类名称。bean 是 customerService 而不是客户(我假设您的意思是这是一个实体?)

关于java - ClassCastException - 客户和客户服务位于加载程序应用程序的未命名模块中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58793556/

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