Search code examples
glassfishjava-ee-6jndi

Inject a file using @Resource and JNDI in JEE6


Is it possible to inject a file using JNDI and @Resource in JEE6?

If so how do I setup and JNDI (file) resource in Glassfish?


Solution

  • If your objective is to configure a properties file as follows:

    @Inject
    @Resource("META-INF/aws.properties")
    Properties awsProperties;
    

    then you want to use a WELD extension which is explained in the WELD documentation here

    It is as simple as adding this to your POM

    <dependency>
       <groupId>org.jboss.weld</groupId>
          <artifactId>weld-extensions</artifactId>
          <version>${weld.extensions.version}</version>
          <type>pom</type>
          <scope>import</scope>
    </dependency>
    

    Otherwise

    See this article for a programmatic approach.

    Or else,

    Store your properties in a DB schema table and use JPA 2.0 to retrieve them using JTA pointing to your JNDI.

    Or if your application is a JSF one:

    1. Add a resource bundle in the faces-config.xml file as follows:

       <application>
          <resource-bundle>
              <base-name>/YourProperties</base-name>
              <var>yourProperties</var>
          </resource-bundle>
      </application>
      
    2. Add the corresponding YourProperties.properties file in your classpath or maven resources folder as follows:
      Maven resource folder

    3. In your container managed bean add the following snippet:

      private String someString;
      
      @PostConstruct
      public void loadProperty(){
          someString = ResourceBundle.getBundle("/YourProperties").getString("prop1");
       }