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
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);
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With