ClassCastException-客户和客户服务是否在加载程序应用的未命名模块中?

问题描述 投票:0回答:1

我正在尝试在主应用程序中调用我的Customer Bean,以测试我的Bean设置正确(我可以看到它们正在创建中,并且出现以下错误:

线程“主”中的异常java.lang.ClassCastException:类com.r00107892.bank.domain.Customer无法转换为类com.r00107892.bank.services.CustomerService(com.r00107892.bank.domain.Customer和com.r00107892.bank.services.CustomerService位于的未命名模块中com.r00107892.bank.MainApp.main(MainApp.java:24)中的加载程序“ app”)

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

我更改了BeanConfig,以使其不再将Customer明确命名为Bean,而是使用ComponentScan。

MainApp

@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();
    }
    }

Customer.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;

}

CustomerService

@Service
public interface CustomerService {

    Customer getCustomerByAccountNumber(int accountNumber);

}

CustomerServiceImpl

public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerDAO customerDao;


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

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

我正在尝试在我的主应用程序中调用我的Customer Bean,以测试我的bean设置正确(我可以看到它们正在创建),并且收到以下错误:线程“ main” java.lang中的异常。 ..

java spring javabeans
1个回答
0
投票

应该是:

© www.soinside.com 2019 - 2024. All rights reserved.