This post demonstrates how to set up beans using applicationContext.xml and how to override bean properties in Spring or Spring Boot applications.
2. Environments
SpringBoot 1.x+
Java 1.8+
3. The Pom.xml
spring boot version:
all dependencies:
4. The database and table
For demo purpose, I setup one database in localhost as follows:
There is a table ‘tbl_student’ in both of the databases:
And insert one record into that table:
5. The domain class Student
6. The applicationContext.xml and properites file
We can define a file named applicationContext.xml in src/main/resources/, here is the content:
Then we need a properties file named jdbc.properties in src/main/resources too.
7. Import the applicationContext.xml into springboot application
Now we can use the annotation @ImportResource to import applicationContext.xml into our springboot application.
What is @ImportResource?
Indicates one or more resources containing bean definitions to import.
Like @Import, this annotation provides functionality similar to the <import/> element in Spring XML. It is typically used when designing @Configuration classes to be bootstrapped by an AnnotationConfigApplicationContext, but where some XML functionality such as namespaces is still necessary.
8. The DAO class
Then we define a Dao class to access the database.
9. The JUnit testcase
Run the testcase, we got a green bar.
10. How to override the property values in jdbc.properties?
You can see that we have used the PropertyPlaceholderConfigurer to configure our application properties in applicationContext.xml, if you want to override the property values in jdbc.properties , you can do as follows:
Step #1: Add property file to the configurer list, change your applicationContext.xml as follows:
Then we change our database’s root password to 1234QWER as follows:
Rerun the junit test, we get green bar too.
It’s so easy, do you think so?
The example code has been uploaded to github, you can visit here to view the example codes.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem.
So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by
email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope: