15 - Spring Intro - Exercise 1
Overview
The objective of this exercise is to set up a simple Spring project using Maven. We will practice creating Spring beans using annotation-based configuration.
Task
In IntelliJ, create a new Maven project using a maven
quickstart
archetype - name itSpringIntro
. You can accept all the default settings.Open up the pom.xml and change the test dependency, your java version and add a dependency for Spring framework.
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.22.RELEASE</version> </dependency> </dependencies>
Delete the example unit test that was created with the project.
In src/main/java/org/example (package name if you accepted the default Maven settings) create a new Java class called
Pet
. ThePet
class has aprivate String name
with constructor, getter and setter for the name.We will now create the Spring Configuration class. In the same package as above, create a new class called
SpringConfig
. Annotate this class with@Configuration
. Make sure the appropriate package is imported.import org.springframework.context.annotation.Configuration;
Define your beans. Inside the
SpringConfig
class, create apublic
method that return aPet
object and call itpet1Bean
. This method does not need any parameters. It needs to be annotated with@Bean
. Inside the method, instantiate yourPet
class and set its name. Return the object from the method.Repeat the above step to create another
Pet
bean -pet2Bean
.Locate your main method if you have one -
App.java
class should have been generated fo you. Within the method, create a reference to your configuration classApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Using this reference, use the getBean() method to access the bean from your container.
Pet pet1 = (Pet) context.getBean("pet1Bean");
Similarly, access the second bean and print out the names of the pets.