1.依赖注入的方式
- 1.通过构造器注入
- 2.通过Setter方法注入
- 3.通过Field属性注入
1.1 通过构造器注入
- 1.官方推荐的方式
- 2.注入对象很多的情况下,构造器参数列表会很长,不灵活
- 3.对象初始化完成后,即可获得可使用的对象
- 4.检测到循环依赖
2.2 通过Setter方法注入
- 1.日常开发中不常见
- 2.可以确保注入前不依赖spring容器
- 3.每个set方法单独注入一个对象,可以灵活控制,可以实现选择性注入
- 4.检测到循环依赖
2.3 通过Field属性注入
- 1.如@Autowired、@Resource注解
- 2.控制了对象的外部可见性,不被spring容器托管的对象无法自动注入
- 3.不能被检测出是否出现循环依赖
- 4.被final修饰的属性,无法赋值
2.代码示例
2.1 构造函数注入
package com.learning.controller;
import com.learning.service.TestService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author wangyouhui
* @Description 测试controller
**/
@RestController
@RequestMapping("/test")
public class TestController {
private TestService testService;
public TestController(TestService testService){
this.testService = testService;
}
@GetMapping("/get")
public String test(){
return testService.test();
}
}
package com.learning.service.impl;
import com.learning.service.TestService;
import org.springframework.stereotype.Service;
/**
* @Author wangyouhui
* @Description 测试实现类
**/
@Service
public class TestServiceImpl implements TestService {
@Override
public String test() {
return "test";
}
}
2.2 setter方法注入
package com.learning.controller;
import com.learning.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author wangyouhui
* @Description setter方法注入
**/
@RestController
@RequestMapping("/test")
public class TestController {
private TestService testService;
@Autowired
public void setTestService(TestService testService){
this.testService = testService;
}
@GetMapping("/get")
public String test(){
return testService.test();
}
}
2.3 field属性注入
ackage com.learning.controller;
import com.learning.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author wangyouhui
* @Description setter方法注入
**/
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/get")
public String test(){
return testService.test();
}
}