简体   繁体   中英

Java EE connect the controller class with the DAO class

I'm trying to connect my controller to DAO class but get UnsupportedOperationException . Here is my controller:

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

and here is my DAO:

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

the error: WELD-000049: Unable to invoke public void com.controller.ContactsController.init() on com.controller.ContactsController@7e7514ca

It seems that I'm failing to inject the DAO referenec into the controller, but I'm not sure what I'm doing wrong

Try this

@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(repository?)

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

edit: You can't inject your repo into your controller, you should place a layer (service) between your controller and repository to manipulate your data before sending it to your views

Just a quick guess ... but have you tried to not initialize your reference in the controller? It should not be necessary to initialize it on your own since you already have a constructor annotated with @Inject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM