/
15 - Spring Intro - Exercise 1

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

  1. In IntelliJ, create a new Maven project using a maven quickstart archetype - name it SpringIntro. You can accept all the default settings.

  2. 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>
  3. Delete the example unit test that was created with the project.

  4. In src/main/java/org/example (package name if you accepted the default Maven settings) create a new Java class called Pet. The Pet class has a private String name with constructor, getter and setter for the name.

  5. 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;

  6. Define your beans. Inside the SpringConfig class, create a public method that return a Pet object and call it pet1Bean. This method does not need any parameters. It needs to be annotated with @Bean. Inside the method, instantiate your Pet class and set its name. Return the object from the method.

  7. Repeat the above step to create another Pet bean - pet2Bean.

  8. 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 class

    ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
  9. Using this reference, use the getBean() method to access the bean from your container.

    Pet pet1 = (Pet) context.getBean("pet1Bean");
  10. Similarly, access the second bean and print out the names of the pets.