Spring Framework is unarguably the most in-demand framework in the Java Enterprise development ecosystem. In this article, I am going to showcase a simple example using Spring Framework.
If you are new to Spring, I encourage you to get a basic understanding of the concepts behind the Spring framework. One of my earlier articles What is Spring Framework can be a good starting point.
In this section, I am going to discuss what do you need to start with:
- Java 8 or higher (JRE isn’t enough. Install Java SDK)
- IDE (I am using IntelliJ community edition)
- Basic knowledge of Spring
It is time to make our hands dirty with code.
2. Getting Started
Create new maven project springdemo and add below dependencies to your project,
I am going to show both XML based configuration and Java-based configuration.
Create a Java bean class
HellowWorld under the package
com.jcg.beans as below,
HelloWorld is a simple Java bean class with a single method. This bean is loaded into the Spring context and the method is consumed in different caller objects.
To load the HelloWorld bean into Spring Context using Java based configuration, create a config file
com.jcg.config package. Refer the below screenshot,
Each of the Java beans is annotated with
@Bean annotation. By default, beans are identified by their type. However, for more specific identification, they can be followed by a name.
Java beans can also be loaded to context using XML based configuration. Below is the sample XML configuration,
Java beans are configured in
<bean/> tag. spring-beans.xml file has to be created in
resources folder, that way
ClassPathXmlConfiguration class can pick it up without the absolute path.
To run the program,
- XML based configuration can be triggered by running
Above class loads, the Spring XML configuration from the classpath and the output of the program is as below,
- Java based configuration can be triggered by running
Above class loads, the beans using annotations and output is as below,
3. How to load Spring beans from context?
In a standalone Spring application, Spring beans can be loaded from the configuration by making use of below classes,
- ClassPathXmlApplicationContext – Open and read xml based application context configuration.
- AnnotationConfigApplicationContext – If you choose to use Java-based configuration instead of XML configuration, you need to use this class.
4. Download The Source Code
In this article, we have learned how a simple Spring program can be created. The example can be downloaded in the below link:
You can download the full source code of this example here: Spring Framework Example