Spring配合Lombok实现依赖注入的新姿势

Spring Bean 的注入方式一般分为三种:

  1. 1.构造器注入
  2. 2.Setter注入
  3. 3.基于注解的 @Autowired 自动装配(Field 注入)


一般常用的是第3种,但在IDEA中使用@Autowired对字段注入时会进行提示:

Field injection is not recommended.
Inspection info: Spring Team recommends: “Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies”

这个是个警告,可以忽视,但是解决这个警告可以用J2EE的@Resource注解来代替@Autowired。但其实这是Spring官方给出的注入建议:

在Spring4.x版本中推荐的注入方式是构造器注入,参数声明为final

@Component
public class MyService {
  private final OtherService other;// 注意final

  //@Autowired  4.3以上可以省略 
  public MyService(OtherService other){
    this.other= other;
  }
}

在Spring4.3或以上版本,使用构造器注入时,可以省略@Autowired注解

但是构造器注入有个缺点:当注入参数较多时,代码臃肿,降低了可读性。

现在比较好的解决方案是Lombok。

只要在类上添加这个注解:
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
Lombok会生成对应的所有Constructor,并在其上添加@Autowired注解.
然后将要注入的对象声明为private final,就可以了。

@RequiredArgsConstructor为每个需要特殊处理的字段生成一个带有1个参数的构造函数。所有未初始化的final字段都将获得一个参数,以及任何标记为@NonNull且未在声明位置初始化的字段。对于那些用@NonNull标记的字段,还将生成显式null检查。如果用于标记为@NonNull的字段的任何参数包含null,则构造函数将抛出NullPointerException。参数的顺序与字段在类中出现的顺序相匹配。
 

@Component
// @RequiredArgsConstructor(onConstructor = @__(@Autowired)) 4.3以下版本
@RequiredArgsConstructor
public class MyService {
    private final OtherService; 
}

Lombok真的是个宝啊! 

参考链接:

推荐基于Lombok的Spring注入方式(基于构造器注入)及快速获取Spring容器中管理的对象_koala、的博客-CSDN博客推荐基于Lombok的Spring注入方式注入方式(基于构造器注入)及快速获取Spring容器中管理的对象Spring注入方式对比推荐一种好用的基于构造器注入的Spring注入方式使用 Lombok 解决构造器注入代码冗余问题快速获取Spring容器中管理的对象https://blog.csdn.net/qq_42937522/article/details/110791736使用LOMBOK实现Spring构造器注入 - 简书之前写依赖注入时都是使用下面这种Field-based Dependency Injection: 今天了解到Spring其实推荐的是另一种构造器注入的方式,如下: 原因是因...https://www.jianshu.com/p/13fa9537b1c4

你可能感兴趣的:(Spring,java,spring,mysql,lombok)