To inject a Datasource in your Enterprise applications you can use the javax.annotation.Resource annotation to declare a reference to that resource.
The @Resource can decorate a class, a field, or a method. The container will inject the resource referred to by @Resource into the component either at runtime or after its initialization.
In the following example, we can see how to inject a DataSource object into a Class field:
@WebServlet("/demo")
public class DemoServlet extends HttpServlet {
@Resource(lookup="java:/PostGreDS")
private DataSource ds;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<h1>Datasource example</h1>");
try (Connection con = ds.getConnection();
PreparedStatement ps = createPreparedStatement(con);
ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
out.write("Time from Database: " +rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private PreparedStatement createPreparedStatement(Connection con) throws SQLException {
String sql = "SELECT NOW();";
PreparedStatement ps = con.prepareStatement(sql);
return ps;
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
By deploying the above Servlet, you will be able to check the current time on a PostgreSQL Datasource which needs to be available on the application server:
To learn how to configure PostgreSQL Database on WildFly we recommend checking this tutorial: Configuring a datasource with PostgreSQL and JBoss/WildFly