【问题标题】:Spring: @Value with lombok in other classSpring:@Value 与其他类中的 lombok
【发布时间】:2020-08-11 07:48:28
【问题描述】:

我们可以将@Value 与 lombok 一起使用吗?

我在下面创建了一个类

@Getter
@Setter
class Hello
{

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

}

是否可以在其他类中重用String url值,使用lombok getter和setter?

【问题讨论】:

  • 当然你可以使用它,但你也可以使用@Value("${url}")将它注入到另一个类中

标签: java spring spring-boot getter-setter lombok


【解决方案1】:

是的,但它仍然需要遵守自动装配规则。你需要给 Spring 的依赖注入框架一个参与的机会。

如果你只是写

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

那么结果将为空。

因为对象可能处于半初始化状态,field injection is usually not a good idea

这与龙目岛无关。该对象需要由 Spring 创建。一种方法是使其成为组件

@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
    }
}

【讨论】:

    【解决方案2】:

    当然。 Lombok 创建 getter 和 setter,默认情况下是公共的,因此任何其他类都可以使用传统的 getter/setter 语法访问它们。在这种情况下,您只需要调用该函数:

    yourHelloObject.getUrl()
    

    【讨论】:

    • 我尝试使用 @Autowired hello,但我无法从 hello 中获取该值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多