Lombok和构造函数注入的最佳实践

Lombok和构造函数注入的最佳实践

本文介绍了@Value字段,Lombok和构造函数注入的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Java Spring应用程序.我的应用程序中有一些使用.yml配置文件配置的字段.我想在有关字段上使用@Value注释导入这些值.我还想使用构造函数注入的最佳实践,而不是使用字段注入,但是我想使用Lombok而不是手动编写我的构造函数.有什么办法可以一次完成所有这些事情?举例来说,这不起作用,但与我想要执行的操作类似:

I'm developing a Java Spring application. I have some fields in my application which are configured using a .yml config file. I would like to import those values using an @Value annotation on the fields in question. I would also like to use the best-practice of constructor injection rather than field injection, but I would like to write my constructor using Lombok rather than manually. Is there any way to do all these things at once? As an example, this doesn't work but is similar to what I want to do:

@AllArgsConstructor
public class my service {
    @Value("${my.config.value}")
    private String myField;

    private Object myDependency;

    ...
}

在这种情况下,我想要的是Lombok生成仅设置myDependency的构造函数,并允许从我的配置文件中读取myField.

In this case, what I want is Lombok to generate a constructor which sets only myDependency, and for myField to be read from my config file.

谢谢!

推荐答案

您需要 @RequiredArgsConstructor 并将 myDependency 标记为最终版本.在这种情况下,Lombok将基于作为参数提交的"required" final生成一个构造函数,例如:

You need @RequiredArgsConstructor and mark myDependency as final. In this case, Lombok will generate a constructor based on 'required' final filed as argument, for example:

@RequiredArgsConstructor
@Service
public class MyService {

    @Value("${my.config.value}")
    private String myField;

    private final MyComponent myComponent;

    //...
}

等于以下内容:

@Service
public class MyService {

    @Value("${my.config.value}")
    private String myField;

    private final MyComponent myComponent;

    public MyService(MyComponent myComponent) { // <= implicit injection
        this.myComponent = myComponent;
    }

    //...
}

由于这里只有一个构造函数,因此Spring注入 MyComponent 没有显式使用 @Autowired 注释.

Since here is only one constructor, Spring inject MyComponent without the explicit use of the @Autowired annotation.

这篇关于@Value字段,Lombok和构造函数注入的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:34