3

Can we use @Value with lombok?

I created a class below

@Getter
@Setter
class Hello
{

    @Value("${url}")
    private String url;

}

Is it possible to reuse the String url value in other class,Using lombok getters and setters?

Rocky4Ever
  • 828
  • 3
  • 12
  • 35

3 Answers3

1

Of course. Lombok creates the getters and setters, public by default, and therefore they are accessible by any other class using the conventional getter/setter syntax. In this case, you'd just need to invoke the function:

yourHelloObject.getUrl()
Carlos M.
  • 21
  • 2
0

Yes, but it still needs to adhere to the rules of autowiring. You need to give Spring's dependency injection framework a chance to get involved.

If you just write

Hello hello = new Hello()
System.out.println(hello.getUrl()); // null

then the result will be null.

Because objects may be left in a half-initialized state, field injection is usually not a good idea.

This is nothing to do with Lombok. The object needs to be created by Spring. One way to do that is to make it a component

@Component
@Getter
@Setter
class Hello
{
    @Value("${url}")
    private String url;
}

...

@Component
public class AnotherComponent {
    public AnotherComponent(Hello hello) { //constructor injection
        System.out.println(hello.getUrl()); //not null
    }
}
Michael
  • 41,989
  • 11
  • 82
  • 128
0

Note: If you're here from a search engine trying to figure out how to do this on immutable classes via copying the annotation to the constructor, be aware that you cannot until this feature is reopened and resolved or this one is.

So long as you're not trying to use immutable objects and constructor injection this should "just work" as is. From your example it looks like you're not doing that but you may have simplified it for StackOverflow (as you should!) but done so slightly too much.

You can try this, add a value to the lombok.copyableAnnotations entry in the lombok.config file for this to work. Note the += as opposed to =.

lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value
Captain Man
  • 6,997
  • 6
  • 48
  • 74