/
15 - Spring Intro - Exercise 2

15 - Spring Intro - Exercise 2

Overview

In this task we will work with Spring Boot and practice creating Spring beans.

Task 1 - Create a Spring Boot project and a Bean

  1. In SpringInitializr website https://start.spring.io/ create a new project. Change the artifact, project and package name as below.

  2. Click the Generate button. It will download your zipped project. Find it in your Downloads folder, unzip it and copy and paste it into your IdeaProjects folder. In your IntelliJ select File-> Open and open up the unzipped folder.

  3. Expand the Maven tab on the right hand side and within Lifecycle double click on install. Wait for it to finish. Make sure you see a Build Success message!

  4. Locate your main method. The class that contains this method should be annotated with @SpringBootApplication . We want to run our application as command-line application rather than on a server. In order to do so, our BootIntroApplication class should implement CommandLineRunner interface.

  5. Next we need to supply the overridden run method. Just below the main method type in this code

    public void run(String ...arg0) throws Exception{ }
  6. We can now create our beans. We can do so directly using the @Component annotation. Create a new java class called Pet. Use the mentioned @Component annotation above the class declaration.

  7. Create a String attribute to hold the pet's name, an empty constructor and setter and getter for the name attribute.

  8. Annotate the setter with @Value("Lola"). This will set the pet's name value to "Lola".

  9. Back in BootIntroApplication class, outside of any method, declare a variable of type Pet. Annotate it with @Autowired. This will tell Spring that we need a bean of type Pet in this class.

  10. You can go ahead and use the pet object in your run method and maybe print out its name.

Task 2 - Create another Bean

  1. Create another class called Owner. Annotate it with @Component annotation.

  2. This class should contain an attribute of type Pet. Since Pet will be a bean, we can autowire it in.

  3. Create a public method called getPetName. This method should return String and does not need any parameters. Return the pet's name (hint: call getName() on the pet object).

  4. Back in BootIntroApplication class, outside of any method, declare a variable of type Owner. It's a bean, so we can autowire it in. You can now delete the variable of type pet. In your run method, use the owner object to get their pet's name.