Loading config files from Wildfly modules
If you are planning to use Wildfly as your application server, there’s one interesting feature. Often an application contains properties that differ from test environment to staging. If we had such properties inside the application, we need to change them while switching the environment. However, if we read them from an external directory, our application remains firm.
/** Approach 1 **/
String secretKey;
if(env.equals("TEST")) {
secretKey = "randomTestValue";
} else if(env.equals("PRODUCTION")) {
secretKey = "realSecretKey";
}
/** Approach 2 **/@Inject
@Property("secret.key")
private String secretKey;
Steps:
- Create a config.properties file with key-value pair.
- Place it outside the application or in your standard configuration folder inside wildfly modules folder. For ex: com/application/configuration/
- Create main folder and also add module.xml.
<module xmlns="urn:jboss:module:1.1" name="com.application.configuration">
<resources>
<resource-root path="."/>
</resources>
</module>
- Add jboss-deployment-structure.xml in the application with following minimal setting. For a web application (WAR) add this file to the
WEB-INF
directory. For an EJB archive (JAR) add it to theMETA-INF
directory.
<jboss-deployment-structure>
<deployment>
<dependencies>
<module name="com.application.configuration" optional="true"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
OR Adding entries to the MANIFEST.MF
file of the deployment.
If the project has no MANIFEST.MF
file, create a file called MANIFEST.MF
.Add a dependencies entry to the MANIFEST.MF
file with a comma-separated list of dependency module names.
Dependencies: com.my-cdi-module meta-inf
Note: We can add a custom annotation as used in the example as @Property to read the key from config.properties. (Stay tuned for next story for additional information about custom annotation)
Thanks !