Java EE vs Spring Boot : Injecting Properties
Theme: Comparing how properties are injected in Java EE to Spring
Prerequisites: You should be familiar with Java. A little knowledge of how things are done in the Java Web Development world would help.
Github URL: https://github.com/ahwinemman/injecting-properties
Properties file: This property file will be stored in src/main/resources folder of the respective projects.
Spring Boot
Spring boot makes it very easy to create stand-alone production-grade Spring based Applications that you can “just run" with minimum configurations.
Injecting properties in spring is as easy as annotating the respective field with the @Value(“${name_of_property}”) as seen below:
This class implements the CommandLineRunner so that the run method gets called once the application starts up so you will find the properties logged into the terminal.
To run this, you
JAVA EE
Injecting properties in Java EE coming from the Spring boot world may appear verbose irrespective it is very easy to understand.
The class below describes the typical way of getting property values using the InputStream.
The @Startup annotation ensures that this process of reading the properties file happens at the start of the application. In essence it initialises a singleton bean at startup of application.
As at Java EE 7, the @Startup annotation only applies to @Singleton beans.
The annotation below is a qualifier and it allows specify the type of property we are injecting.
To successfully inject properties in Java EE, you need the @Produces annotation which allows the injection of primitives (such as int, long, float…). You cannot also inject classes such as String or Date because these classes are packaged in the rt.jar file which is missing a beans.xml deployment descriptor file.
The @Produces annotation provides a way for us to circumvent this limitation. The Injection API does some heavy lifting for us by taking note of where the qualifier is being injected and then getting the respective property field value. Do note that the the methods below have to be annotated with both @Produces and @StringProperty annotations.
This project is built to be as similar as possible to the Spring boot project. Do note: The MainClass of the Spring boot project is very similar to the MainClass below. The classes will be initiated at application startup and much like the run method is called immediately, the @PostConstruct annotated method below will be called immediately.
To inject, we annotate the field with the @Inject as well as the qualifier @StringProperty(value = “name_of_property”)
To run any of the projects, you could simply build and then run the resulting image based of the Dockerfile included in the respective repositories
Github URL: https://github.com/ahwinemman/injecting-properties
Do clap, comment and suggest future articles you would like me to cover if enjoyed this.