您好,我正在做一个简单的spring应用程序,由于某种原因出现了这个错误:
类型不匹配:无法从对象转换为AccountDAO
我有3个课程,AccountDao:
package com.luv2code.aopdemo.dao;
import org.springframework.stereotype.Component;
@Component
public class AccountDAO {
public void addAccount() {
System.out.println(getClass() + ": DOING MY DB WORK: ADDING AN ACCOUNT");
}
}
DemoConfig:
package com.luv2code.aopdemo;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.luv2code.aopdemo")
public class DemoConfig {
}
和MainDemoApp:
package com.luv2code.aopdemo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.luv2code.aopdemo.dao.AccountDAO;
public class MainDemoApp {
public static void main(String[] args) {
//read spring config java class
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
//get the bean from spring container
AccountDAO theAccountDAO = context.getBean("accountDAO", AccountDAO.class); //THE PROBLE IS HERE
//call the business method
theAccountDAO.addAccount();
//close the context
context.close();
}
}
该错误是在MainDemoApp中的AccountDAO处发生的。accountDAO= context.getBean(“ accountDAO”,AccountDAO.class);
(仅=之后的部分为红色)
最佳答案
你可以尝试一下:AccountDAO theAccountDAO = (AccountDAO) context.getBean("accountDAO", AccountDAO.class);