Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CDI's dependency injection support #267

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

CDI's dependency injection support #267

wants to merge 1 commit into from

Conversation

salvadormarcos
Copy link

@salvadormarcos salvadormarcos commented Jan 28, 2017

I tried using dependency injection (Java EE's CDI) with Sql2o and didn't work. It would be a very useful feature.

Just add a no-arg constructor in Sql2o and Connection classes. I did it and decided to share.

@eliandroribeiro
Copy link

eliandroribeiro commented Jan 28, 2017 via email

@salvadormarcos
Copy link
Author

I created the producer methods as code below, but the CDI threw an exception requiring a no-arg constructor.

public class ConnectionProducer {
    @Produces
    @ApplicationScoped
    public Sql2o createSql2o() {
        return new Sql2o("jdbc:hsqldb:mem:aname", "SA", "");
    }
    
    @Produces
    @RequestScoped
    public Connection openConnection(Sql2o sql2o) throws SQLException {
        return sql2o.open();
    }
    
    public void closeConnection(@Disposes Connection conn) {
        conn.close();
    }
}

The only way to work without changing Sql2o would be to replace @ApplicationScoped and @RequestScoped by @singleton.
However, in a web application, share the same connection between multiple requests would be a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants