Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJB3.1 properties file injection

is there some simple way to inject Properties class loaded with a file from the classpath into EJB (3.1)?

Something like this:

@Resource(name="filename.properties", loader=some.properties.loader)
private Properties someProperties;

Thank you,

Bozo

like image 595
bozo Avatar asked Oct 10 '22 09:10

bozo


2 Answers

As bkail said, you can achieve this in the following way. I am not sure what your loader=some.properties.loader really meant, so skipped doing anything with that, but provided option for that in case you want to load using the loader.getClass().getResourceAsStream ("filename.properties");

First define your injection type

@BindingType
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD,
        ElementType.PARAMETER })
public @interface PropertiesResource {

    @Nonbinding
    public String name();

    @Nonbinding
    public String loader();

}

Then create a producer for that

public class PropertiesResourceLoader {

    @Produces
    @PropertiesResource(name = "", loader = "")
    Properties loadProperties(InjectionPoint ip) {
        System.out.println("-- called PropertiesResource loader");
        PropertiesResource annotation = ip.getAnnotated().getAnnotation(
                PropertiesResource.class);
        String fileName = annotation.name();
        String loader = annotation.loader();
        Properties props = null;
        // Load the properties from file
        URL url = null;
        url = Thread.currentThread().getContextClassLoader()
                .getResource(fileName);
        if (url != null) {
            props = new Properties();
            try {
                props.load(url.openStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return props;
    }
}

Then inject it into your Named component.

@Inject
@PropertiesResource(name = "filename.properties", loader = "")
private Properties props;

I did this looking into the weld documentation where the @HttpParam is given as an example here. This is as per weld 1.1.0, in weld 1.0.0, the getting annotation can be done like this

PropertiesResource annotation = ip.getAnnotation(PropertiesResource.class);
like image 65
prajeesh kumar Avatar answered Oct 12 '22 23:10

prajeesh kumar


If the application server you are using has WELD as the CDI implementation (Glassfish 3.x or JBoss 7.x or Weblogic 12 are examples) 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>
like image 32
Sym-Sym Avatar answered Oct 13 '22 01:10

Sym-Sym