ClassCastException - Customer и Customerservice находятся в неназванном модуле приложения-загрузчика? - PullRequest
0 голосов
/ 11 ноября 2019

Я пытаюсь вызвать мой клиентский компонент в моем основном приложении, чтобы проверить правильность настройки моего компонента (я вижу, что он создается), и получаю следующую ошибку:

Исключениев потоке "main" java.lang.ClassCastException: класс com.r00107892.bank.domain.Customer не может быть приведен к классу com.r00107892.bank.services.CustomerService (com.r00107892.bank.domain.Customer и com.r00107892. bank.services.CustomerService находится в безымянном модуле загрузчика «app») по адресу com.r00107892.bank.MainApp.main (MainApp.java:24)

Я проверил свой Customer.java, CustomerDAO.java, CustomerDAOImpl.java, CustomerService.java, CustomerServiceImpl.java, мой mainApp и мой BeanConfig.java, и я не могу найти проблему.

Я изменил свой BeanConfig, чтобы он больше не называл «Клиент в качестве Бина» явно и использовал 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 (уже в базе данных), который будет распечатан.

1 Ответ

0 голосов
/ 11 ноября 2019

должно быть:

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

Вы не присваивали имя бобам, поэтому по умолчанию оно будет принимать имя класса. Боб - это customerService, а не клиент (я полагаю, вы подразумевали, что это сущность?)

...