Skip to main content

QBean Support

git checkout qbean-support

In order to follow this section, git checkout qbean-primer.

jPOS provides an abstract helper class org.jpos.q2.QBeanSupport that implements a QBean basic functionality.

It implements the basic init → start → stop → destroy lifecycle methods and call the protected counterparts initService, startService, stopService, and destroyService, catching possible exceptions and logging them. It also expose some attributes and operations as MBeans, by implementing the QBeanSupportMBean interface.

Taking away some boilerplate code, the methods are implemented like this:

    @Override
public void init () {
try {
initService();
} catch (Throwable t) {
log.warn ("init", t);
}
}

and same goes for the start, stop and destroy methods.

Changing our MyQBean code to use QBeanSupport is straight forward, our MyQBean class would look like this:

package org.jpos.tutorial;

import org.jpos.q2.QBeanSupport;

public class MyQBean extends QBeanSupport {

@Override
protected void initService() {
logState();
}

@Override
protected void startService() {
logState();
}

@Override
protected void stopService() {
logState();
}

@Override
protected void destroyService() {
logState();
}

private void logState() {
getLog().info (getName() + ":" + getStateAsString());
}
}

We don't need the MyQBeanMBean interface anymore, because QBeanSupport implements QBeanSupportMBean that already expose the same operations to JMX, although we can keep it if our QBean wants to expose additional attributes or operations.

In this example, we made a little change to the qbean descriptor located at src/dist/deploy/60_myqbean.xml, it now reads:

<myqbean class="org.jpos.tutorial.MyQBean" logger="Q2" />

See we assign a logger to the service, in this case the Q2 logger, defined in deploy/00_logger.xml.

You might have noticed that we have renamed the printState method that printed the state to stdout to logState that outputs to a jPOS logger. First of all, in the prevous example, the System.out.println call was captured by the log because the logger configuration (defined in deploy/00_logger.xml) has the following properties:

<property name="redirect" value="stdout, stderr" />

So our System.out.println was captured by the log that monitors the System.out stream. A call to System.err.println would do a similar thing, capturing System.err.

Now, by calling getLog().info(...) within our class that extends QBeanSupport, we tap into the logging capabilities configured in 60_myqbean.xml. This seamless integration, a bit like magic provided by Q2, is made possible through our implementation of IoC (Inversion of Control). We employed a 'push' configuration method using reflection long before Java introduced support for annotations.

Q2 MAGIC

If a QBean has a public void setLogger (String loggerName) method, or implements the org.jpos.util.LogSource interface, Q2 will take care of calling it during the initialization phase of your QBean.