Refresh
this page because I am probably still making changes
to it.
Lombok is a bean management framework,
although you can use it with most classes, not just beans.
It's one of several cool dependencies you can add to your
Spring projects to automate more tedious tasks. In this case, Lomok
allows you to automate the coding of things like
a bean's constructors, accesors, mutators, equals(), toString(), etc.
It's also really easy to override/customize whatever methods you want.
Lombok
First, we have to add Lombok to your Eclipse installation,
then you can add the Lombok dependency
to your project(s).
Install Lombok into Eclipse
To add Lombok to Eclipse, perform the following steps:
In the Eclipse menu, select Help > Install New Software
In the "Work With" field, enter https://projectlombok.org/p2 and then press ENTER
The list below that should show an entry for Lombok. If it's not
selected, select it. Then click NEXT.
The next screen asks you to review the items you're installing.
Click NEXT.
Accept the terms of the license agreement and accept any
certificates, if prompted.
If you get a dialog asking "Do you trust these signers?"
check the Project Lombok item in the list and click
the TRUST SELECTED button.
Restart Eclipse when prompted.
Adding the Lombok Dependency
Now we can add the Lombok dependency to a project and start working
with it. Start a new project, and in the Dependencies screen, make
sure you add Spring Web, Spring Boot DevTools, Thymeleaf,
and Lombok.
If you ever need to add Lombok to an existing project, just add the
following dependency to your POM file (check your version
number and update the version below as appropriate):
Lombok consists of several annotations
that you add to your Beans/classes.
These annotations tell Lombok what code to add to your class!
To see an example, add a .beans package to your project and add a
Bean called Inventory
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
}
Now add a couple of data members to the Inventory bean: Let's add
a long integer ID for the inventory item's id number, and
a String for the inventory item's name:
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private long itemId;
private String itemName;
}
Here's where things get interesting. We figure we probably need a
default constructor and a 2-param constructor. Instead of adding
them, we're going to use Lombok to create them for us.
First, add the wildcard import lombok.*
to your class. Normally we don't like to use wildcards, but
it's safe to do just for this example.
Normally you should use specific imports of each annotation.
Now go right above the class header of the Inventory class and
add the annotation @NoArgsConstructor
Can you guess what this does? If you guessed that it adds a no-argument
constructor (a default constructor), you'd be correct!
After adding it, you might notice that the Outline window to the right
shows a list of all your Inventory class's members, and there
should now be a default constructor in that list!
Now add one for the 2-param constructor. Under (or above, it really
doesn't matter), add the annotation @AllArgsConstructor.
Notice that now a 2-param constructor appears!
The 2-param constructor that was added by Lombok is a basic
one with no validation, so if you wanted to add validation
to your constructor (and you would, if your set-methods
perform validation) then you'd have to add your constructor manually,
instead. But that's not a huge deal when you see what else
Lombok annotations can do!
Let's use Lombok to add some accessors and mutators.
There are a couple of ways to do this. You can do this
individually for members, which is nice if you've got
some members that need accessors and some that don't.
For example, above the itemID member, add the annotations
@Getter and @Setter.
Now you should see getItemId() and setItemId()
in your navigator window. Do the same thing to itemName and watch
those methods appear, too.
Another cool thing is that Lombok will update everything
if you decide to add more data members. For example,
add a private int data
member quantity for
the number of items, and add the @Getter and @Setter to it.
Notice how the accessor and mutator for quantity are added,
and the 2-param constructor now becomes a 3-param
constructor!
Normally we validate our members in the mutator, but Lombok doesn't
do that for us. If we need to, we just add the set-method ourselves.
No problem. Remove @Setter from itemID and add your own:
the item ID must be greater than 0. Do the same for
quantity: quantity must be 0 or greater.
You might notice that once you make these changes, the
setItemId() and setQuantity() are still in the outline,
but they may have moved down to the bottom of the list.
Now, since we've added our own mutator for itemID and
quantity, we should
call it from the 3-param constructor. So remove the
@AllArgsConstructor annotation from your class and
add the 3-param constructor yourself. As with the mutators,
you'll notice the 3-param constructor moves near the bottom
of the outline. These items are listed in the order in which
they appear in your code, with the Lombok-generated methods
first.
We can also add a toString() method by adding the
@ToString annotation to our class. This creates
a default toString() method, but if you read
the documentation, you can customize the toString()'s
return value a bit.
There are lots of other annotations you'll find useful. Here's
a summary of the ones you'll use most often, with links
to their documentation:
Annotations attached to the class header:
@ToString - adds a
toString() method
that returns the state of your object as a String.
See the documentation on how you can customize the toString()'s
return value!
@EqualsAndHashCode
- adds default equals() and hashCode() methods to your class.
@RequiredArgsConstructor adds a constructor that contains
parameters for each data member that is marked with
@NonNull
@AllArgsConstructor adds a constructor with a param for
each private data member
@Data - A shortcut for
@ToString, @EqualsAndHashCode,
@Getter on all fields, @Setter on all non-final fields,
and @RequiredArgsConstructor. So basically, adding
@Data to the class will add all of those things!
Annotations attached to individual data members:
@NonNull - performs
a check for null on the parameter
and throws NullPointerException if a parameter passed into
the member's mutator is null.
@Getter,
@Setter - attach this one to a data member
to add a getter or setter method (accessor or mutator)
to this member. Note the mutators will have no validation.
Did you notice the item @Data? Did you try it? Try it!
Remove the @Getter and @Setter from each member, remove the
@ToString from the class, and add @Data to the class instead.
Look at all the methods it adds! Cool!
Notice also that even though @Data adds mutator methods for
all data members, it doesn't bother adding one for itemID
because we added that one ourselves. Lombok is very
considerate!
Exercises
1. Create the following bean (you can add it
to this project's .beans package) that models
an appointment that a teacher might have
with one of their students on a specific
date. Use Lombok where it is appropriate.
Student ID must be greater than 0 and the default is 990000000.
LocalTime defaults to 12:00 pm. An invalid LocalTime can't
be constructed (it would throw an exception) so we don't have
to worry about validating it (if someone's passing in a time
object, they must have been able to construct one in the first
place).
Topic can be anything and there is no default since
topic is optional.
Challenge: toString() should only display the student
id and the appointment time, not the topics. Do this
with Lombok only.
2. Add the latest version of your Book
bean to the project. Update it so that it makes use of
Lombok. You'll need to delete the methods you don't need
anymore, but you'll have to keep a few (such as the
mutators that do the validation, for example).