User Tools

Site Tools


jboss_7_cookbook

Deployments

Modules

Webservices

Dependency Injection

JBoss uses Java CDI

Resource Initialisation

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

Bootstrap Servlet

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)
	}
 
 
}

Database Connectivity

Configure a Datasource

  • Copy the JDBC4 driver to …./jboss/standalone/deployments
    • JBoss automatically deploys JDBC4 drivers
    • for older JDBC drivers look here
  • Configure the Datasource from the JBoss Web Console or by editing standalone.xml

Option1: Configure Datasource from JBoss Web Console

  • click “Profile” in the upper right corner
  • click “Connector –> Datasources” on the left side
  • click “Add” and define connection
  • dont forget to enable the connection

Option2: Configure Datasource in standalone.xml

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>

Access the Datasource in Java

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 ..... ");
jboss_7_cookbook.txt · Last modified: 2013/12/23 13:09 by hkoller