Reputation: 742
How I can set a Data Source dynamically? Like below in Spring:
@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/userbase");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("root");
return driverManagerDataSource;
}
Can I import just this functionality from Spring to a Java EE 7 enterprise application?
Upvotes: 1
Views: 1521
Reputation: 19445
Any Java EE 7 implementation will have facilities for defining a javax.sql.DataSource that has a name in the server's JNDI directory.
You can inject a reference to it in your application client class using the javax.annotations.Resource annotation and the use it something like:
public class SomeDatabaseClient {
@Resource("jdbc/myDataSource")
javax.sql.DataSource myDataSource;
public void useTheDatabase(String username, String password) {
try (Connection con = myDataSource.getConnection(username, password);
PreparedStatement ps = con.prepareStatement(...);
ResultSet rs = ps.executeQuery() {
// process the result set
...
} catch (SQLException e) {
// handle errors
}
}
}
If you don't need to specify the database credentials dynamically they can be included in the DataSource definition in the server.
Note that managing user passwords securely is not trivial so you need a pretty good reason to be using them in this fashion.
You can also set up your Spring Framework configuration to work like this with the same code if that is what you need.
Upvotes: 1