Java, Software Development, Spring

Spring Dependency Injection Examples Without Spring Boot

The Spring Framework has come a long way. Nowadays, it is way easier to start a Java project with the Spring Framework using Spring Boot. In the past, we used to download Spring individual jar files and configure the dependencies manually. Even though we had Apache Maven, things were still tricky, especially for relatively huge projects. With Spring Boot, developers now can focus more on implementing the business requirements. However, those who have just started learning Spring may find it has a steep learning curve. This post shows how to create a Spring Dependency Injection examples without using Spring Boot to get a better understanding of how things work.

Create A Java Project With Maven

Before we start working with the Spring Framework, we need a Maven project. Please go through the Create Java Project Using Maven in Command-Line post to create that Maven project.

Get Spring Core Dependencies From Maven Central

The latest version of Spring as of this writing is 5.28.RELEASE. Go to the online Maven Repository and copy the XML snippets as shown below and place them between the <dependencies> tags in pom.xml.

For our Spring dependency injection example, we only need five dependencies.

Dependency Injection Example With @ComponentScan

In this example, we use @ComponentScan to pick up all classes with @Component annotations from a specific package – com.turreta.mavenproj.

For this example, we need to change the MyConfiguration class as follows.

Commenting out the annotation prevents the following run-time error.

Using Java Configuration

We will not use XML configuration because it is ancient, and we already stepped away from Spring Boot to make a dependency injection example. To keep things simpler, we will stick with Java configuration classes. Note the App class has different codes now.

The MyConfiguration class has the following content.

Those are examples of Spring Dependency Injection without Spring Boot.

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *