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
In SpringInitializr website https://start.spring.io/ create a new project. Change the artifact, project and package name as below.
Click the
Generate
button. It will download your zipped project. Find it in your Downloads folder, unzip it and copy and paste it into yourIdeaProjects
folder. In your IntelliJ selectFile
->Open
and open up the unzipped folder.Expand the Maven tab on the right hand side and within
Lifecycle
double click oninstall
. Wait for it to finish. Make sure you see a Build Success message!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, ourBootIntroApplication
class should implementCommandLineRunner
interface.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{ }
We can now create our beans. We can do so directly using the
@Component
annotation. Create a new java class calledPet
. Use the mentioned@Component
annotation above the class declaration.Create a
String
attribute to hold the pet's name, an empty constructor and setter and getter for the name attribute.Annotate the setter with
@Value("Lola")
. This will set the pet's name value to "Lola".Back in
BootIntroApplication
class, outside of any method, declare a variable of typePet
. Annotate it with@Autowired
. This will tell Spring that we need a bean of typePet
in this class.You can go ahead and use the pet object in your run method and maybe print out its name.
Task 2 - Create another Bean
Create another class called
Owner
. Annotate it with@Component
annotation.This class should contain an attribute of type
Pet
. SincePet
will be a bean, we can autowire it in.Create a public method called
getPetName
. This method should returnString
and does not need any parameters. Return the pet's name (hint: callgetName()
on the pet object).Back in
BootIntroApplication
class, outside of any method, declare a variable of typeOwner
. 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.