Spring tutorial to read .proprties files

Q1. How do you read properties file in spring?
A1. PropertyPlaceholderConfigurer allows you to share a properties files. You can simply share one properties file for all of your build info or you can separate things out, and have multiple properties files in your build script.

STEP 1: Prepare the properties file to use. The myapp.properties file contains name/value pairs as shwon below.

STEP 2: Define the interface and the implementation classes that read these properties.

The statuses are read from the above properties file.

STEP 3: The beans3.xml that read properties file and inject relevant values.

STEP 4: Finally, the standalone client application that makes use of the OrderNotification.

If you run the above stand-alone application, you get the following output

Q2. How would you go about reading environment specific property files?
A2. The properties file can be loaded via a file system.

STEP 1: Have the properties files in an external file system and not within the war or ear archives.

STEP 2: The beans3.xml will have the following change — change classpath: to file:

STEP 3: Provide the JVM arguments PROPERTIES_HOME and ENV.

STEP 4: The rest remain the same as previous example.

Q. How do you inject a java.util.Properties into your OrderNotification?

STEP 1: Modify the OrderNotificationImpl as shown below. As you can se the, the java.utilProperties will be injected via setter injection.

STEP 2: Make some changes to the wiring. The beans4.xml uses the PropertiesFactoryBean and pass it to the PropertyPlaceholderConfigurer. Also, notice that the myappProperties is injected into orderNotification via setter injection.

STEP 3: Finally, modify the TestSpring3 to use beans4.xml.

The output will be:

Q. How would you use annotations to inject properties?
A. Spring 3.0 makes use of annotations, and the properties can be injected

300+ Java Developer Interview Q&As

800+ Java Interview Q&As