我尝试在主应用程序中调用我的Customer Bean,以测试Bean设置是否正确(我可以看到它们正在创建),但收到以下错误:
线程“main”中出现异常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)
我已检查了我的Customer.java、CustomerDAO.java、CustomerDAOImpl.java、CustomerService.javaCustomerServiceImpl.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();
}
}
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;
}
客户服务
@Service
public interface CustomerService {
Customer getCustomerByAccountNumber(int accountNumber);
}
客户服务实施
public class CustomerServiceImpl implements CustomerService {
@Autowired
CustomerDAO customerDao;
public Customer getCustomerByAccountNumber(int accountNumber) {
return customerDao.findById(accountNumber);
}
我希望看到客户名称为帐户编号1(已在数据库中)打印出来。
1条答案
按热度按时间pu82cl6c1#
应为:
您没有为bean指定名称,因此默认情况下它将使用类名。bean是customerService而不是customer(我假设您的意思是这是一个实体?)