Ert*_*i87 2 java spring constructor-injection lombok
我正在开发Java Spring应用程序。我的应用程序中有一些使用.yml配置文件配置的字段。我想在有关字段上使用@Value注释导入这些值。我还想使用构造函数注入的最佳实践,而不是使用字段注入,但是我想使用Lombok而不是手动编写我的构造函数。有什么办法可以一次完成所有这些事情?例如,这不起作用,但与我想要执行的操作类似:
@AllArgsConstructor
public class my service {
@Value("${my.config.value}")
private String myField;
private Object myDependency;
...
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想要的是Lombok生成仅设置myDependency的构造函数,并使myField从配置文件中读取。
谢谢!
小智 10
男性确保您至少使用Lombok 的1.18.4版本。并且您已将所需的注释添加到lombok.config文件中。
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Value
Run Code Online (Sandbox Code Playgroud)
这是你的课:
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class MyService{
@Value("${my.config.value}")
private String myField;
private Object myDependency;
}
Run Code Online (Sandbox Code Playgroud)
这是 lombok 生成的类:
public class MyService {
@Value("${my.config.value}")
private String myField;
private Object myDependency;
@Autowired
@Generated
public MyService(@Value("${my.config.value}") final String myField, final Object myDependency) {
this.myField = myField;
this.myDependency = myDependency;
}
Run Code Online (Sandbox Code Playgroud)
PS:确保您在 /src/main/java 文件夹下有lombok.config文件。我尝试将其添加到 /src/main/resources 中,但没有奏效。
从这里采取的回应。
您需要将@RequiredArgsConstructor其标记myDependency为final。在这种情况下,Lombok将基于作为参数提交的“ required” final生成一个构造函数,例如:
@RequiredArgsConstructor
@Service
public class MyService {
@Value("${my.config.value}")
private String myField;
private final MyComponent myComponent;
//...
}
Run Code Online (Sandbox Code Playgroud)
这等于以下内容:
@Service
public class MyService {
@Value("${my.config.value}")
private String myField;
private final MyComponent myComponent;
public MyService(MyComponent myComponent) { // <= implicit injection
this.myComponent = myComponent;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
由于这里只有一个构造函数,因此Spring MyComponent 无需显式使用@Autowired注解即可进行注入。
| 归档时间: |
|
| 查看次数: |
3184 次 |
| 最近记录: |