Java EE将控制器类与DAO类连接起来

时间:2019-01-28 12:13:00

标签: java java-ee

我正在尝试将控制器连接到DAO类,但得到Number。这是我的控制器:

UnsupportedOperationException

这是我的DAO:

@Named("contactsController")
@SessionScoped

public class ContactsController implements Serializable {
    private static final long serialVersionUID = 1L;

    protected List<Contact> contacts;

    protected ContactsDAO contactsDAO = new ContactsDAOImp();

    @Inject
    public ContactsController(ContactsDAO contactsDAO) {
    this.contactsDAO = contactsDAO;
    }

    public List<Contact> getContacts() {
        return contacts;
    }

    @PostConstruct
    public void init() {
        this.contacts = contactsDAO.getAllContacts();
    }
}

错误: @Named @ApplicationScoped public class ContactsDAOImp implements Serializable, ContactsDAO { // DAO code here }

似乎我无法将DAO Referenec注入到控制器中,但是我不确定自己做错了什么

2 个答案:

答案 0 :(得分:2)

尝试一下

@Named("contactsController")
@SessionScoped
public class ContactsController implements Serializable {

    private static final long serialVersionUID = 1L;
    private List<Contact> contacts;

    @Inject
    private ContactsDAOImp contactsDAOImp;

    public ContactsController() { }

    public List<Contact> getContacts() {
        return contacts;
    }

    @PostConstruct
    public void init() {
        this.contacts = contactsDAO.getAllContacts();
    }
}

ContactDAO(存储库?)

@Named
@ApplicationScoped
public class ContactsDAOImp implements Serializable, ContactsDAO {
    // DAO code here
}

编辑:您无法将回购注入控制器,您应该在控制器和存储库之间放置一个层(服务)以处理数据,然后再将其发送到视图中

答案 1 :(得分:0)

快速猜测...但是您是否尝试过不初始化控制器中的引用?既然您已经有一个用@Inject注释的构造函数,则不必自己进行初始化。