JBoss uses Java CDI
Sometimes Resources should be intitialized as soon as an application is deployed in the container. This may not be as straightforward as one would hope, because JBoss does a lot of lazy initialising. This section shows a few options
Create a servlet which gets loaded at startup. Do resource initialization in there. This can also be used to initialize @ApplicationScoped CDI Singletons:
@WebServlet(loadOnStartup = 1) public class BootstrapServlet extends HttpServlet { @Inject MyExpensiveSingletonResource cdiResource; // cdiResource gets initialized here @Override public void init() { // do additional resource initialization here } @Override public void destroy() { // SHOULD be called when the app shuts down (but better don't count on it) } }
edit …./jboss/standalone/configuration/standalone.xml
<subsystem xmlns="urn:jboss:domain:datasources:1.0"> <datasource jta="false" jndi-name="java:jboss/datasources/CompassDS" pool-name="CompassDS" enabled="true" use-ccm="false"> <connection-url>jdbc:postgresql://192.168.0.20/db-name</connection-url> <driver-class>org.postgresql.Driver</driver-class> <driver>postgresql-9.1-902.jdbc4.jar</driver> <pool> <min-pool-size>0</min-pool-size> <max-pool-size>2</max-pool-size> </pool> <security> <user-name>username</user-name> <password>password</password> </security> <validation> <validate-on-match>false</validate-on-match> <background-validation>false</background-validation> </validation> <statement> <share-prepared-statements>false</share-prepared-statements> </statement> </datasource>
InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup("java:jboss/datasources/CompassDS"); Connection con = ds.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT ..... ");