Sunday, October 28, 2012

Lombok and Spring: IntelliJ Plugin

As indicated in my last post, I've been playing around with Project Lombok a little. One of the easier to absorb features is the @Getter/@Setter annotations, which removes the need to explicitly define getters and setters in your Java classes.

I use IntelliJ as my main IDE. However, when I started to use Lombok, I would get error messages from the IDE when viewing a Spring configuration file that used setter injection.

The answer to this problem was to simply install the lombok-intellij-plugin, which fixed the error rather nicely.

We'll setup the scenario withe simplest of objects that I can think of. If you now have the answer you're looking for (and you probably do), feel free to skip the example below:

    public class Person {

        private String name;

        public Person() {}

        public Person(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

A very simplisitc Spock specification that uses Spring testing to inject an instance of a Person:

    @ContextConfiguration
    class PersonSpec extends Specification {

        @Autowired
        Person person

        def "has a name"() {
            expect: person.name == 'Rudiger'
        }
    }

And the bean that is autowired in from PersonSpec-context.xml:

    <bean id="rudiger" class="prystasj.lombok.plugin.example.Person">
        <property name="name" value="Rudiger"/>
    </bean>

Here the test passes and there is no "red" for errors in our IDE.

Now if we replace the getter and setter in the Person with annotations from Lombok:

    public class Person {

        @Getter @Setter
        private String name;

        public Person() {}

        public Person(String name) {
            this.name = name;
        }
    }

The tests still passes, but our IDE is showing us some red when viewing the Spring configuration file:

At this point, installing the lombok-intellij-plugin sends the error away.

No comments:

Post a Comment