三种注入方式

1. 注解注入

@Controller
public class TestController {
  @Autowired
  private TestService testService;
   
}

注解注入,一般是注入另一个bean

2. 构造器注入

@Controller
public class TestController {
   
  private final TestService testService;
   
  @Autowired
  public FooController(TestService testService) {
      this.testService = testService;
  }

}

构造器注入,配置bean一并配置constructor

3. 使用构造函数注入(Spring4.x推荐)

使用Lombok的@RequiredArgsConstructor来直接构建构造函数

或者

@AllArgsConstructor,不使用Lombok

又或者

用第2点的方法,自己写构造函数

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
//@AllArgsConstructor
public class PmsCategoryServiceImpl implements PmsCategoryService {

    private final PmsCategoryMapper pmsCategoryMapper;
}

4. setter注入

@Controller
public class TestController {
   
  private TestService testService;
   
  @Autowired
  public void setFooService(TestService testService) {
      this.testService = testService;
  }
}

Setter注入,配置property 

推荐使用构造器注入

posted @ 2022-03-01 21:53  何笑笑  阅读(319)  评论(0)    收藏  举报