jakarta-eesingletonstatelessejb-jar.xml

@Singleton bean to read values from ejb-jar.xml


I have a ConfigParameter SLSB that reads configuration values from the ejb-jar.xml file.

This class has only private fields and for each field a corresponding getter method. In my application I have a lot of other EJBs that use an instance of ConfigParameter to read the configuration values.

Now, I thought it would be good idea to make ConfigParameter a @Singleton, since its state is shared across the whole application.

But in the ejb-jar.xml I can set session-type only to Stateful or Stateless. The file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0">
  <enterprise-beans>    
    <session>
      <ejb-name>ConfigParameter</ejb-name>
      <ejb-class>myapp.util.ConfigParameter</ejb-class>      
      <session-type>Stateless</session-type> <!-- make this a Singleton -->
      <env-entry>
        <env-entry-name>adminRoleName</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>admin</env-entry-value>
      </env-entry>
    </session>
  </enterprise-beans>
</ejb-jar>

My questions are:

  1. Is it a good idea to make this bean a singleton?
  2. If yes, how can I achieve this?
  3. For understanding: Why is it not allowed to set session-type to Singleton?

Solution

  • You're using EJBs 3.0. Singleton EJBs were introduced in EJB 3.1. If you want to define it in ejb-jar.xml you should define appropriate version (note the version attribute and XSD location changed to 3.1)

    <ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd" 
        version="3.1">
    

    Or just use @Singleton annotation on the EJB class itself.

    And yes - I would definitely say that it's appropriate to mark application-wide configuration bean as Singleton.