首页 > 解决方案 > 类型不匹配:无法从 Object 转换为 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");

    }

}

演示配置:

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

    }

}

错误出现在 AccountDAO 的 MainDemoApp 中 theAccountDAO = context.getBean("accountDAO", AccountDAO.class); (只有=之后的部分是红色的)

标签: javaspring

解决方案


你可以试试这个:

AccountDAO theAccountDAO = (AccountDAO) context.getBean("accountDAO", AccountDAO.class);


推荐阅读