'ClassCastException - Customer and Customerservice are in unnamed module of loader app?
I am trying to call my Customer Bean in my main app to test that my bean set up is correct (I can see them being created), and am getting the following error:
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)
I have checked my Customer.java, CustomerDAO.java, CustomerDAOImpl.java, CustomerService.java, CustomerServiceImpl.java, my mainApp and my BeanConfig.java and I can't find an issue.
I changed my BeanConfig so that it no longer explicitly named Customer as a Bean and uses 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);
}
I expect to see Customer name for account no 1 (already in database) to be printed out.
Solution 1:[1]
should be:
CustomerService customerService = (CustomerService) context.getBean("customerService");
You did not assign a name to the beans, so by default it will take the class name. The bean is the customerService and not the customer (I assume you meant this to be an entity?)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nir Levy |
