其他分享
首页 > 其他分享> > 三种注入方式

三种注入方式

作者:互联网

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. setter注入

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

Setter注入,配置property 

推荐使用构造器注入

标签:testService,方式,private,Controller,三种,TestService,public,注入
来源: https://www.cnblogs.com/H2z2H/p/15952698.html