> 文章列表 > 【spring】spring依赖注入的方式

【spring】spring依赖注入的方式

【spring】spring依赖注入的方式

目录

        • 一、依赖注入的方式
        • 二、通过构造器注入
        • 三、通过Setter方法注入
        • 四、通过Field属性注入
        • 五、代码示例
          • 5.1 构造函数注入
          • 5.2 setter方法注入
          • 5.3 field属性注入

一、依赖注入的方式

  • 1.通过构造器注入
  • 2.通过Setter方法注入
  • 3.通过Field属性注入

二、通过构造器注入

  • 1.官方推荐的方式
  • 2.注入对象很多的情况下,构造器参数列表会很长,不灵活
  • 3.对象初始化完成后,即可获得可使用的对象
  • 4.检测到循环依赖

三、通过Setter方法注入

  • 1.日常开发中不常见
  • 2.可以确保注入前不依赖spring容器
  • 3.每个set方法单独注入一个对象,可以灵活控制,可以实现选择性注入
  • 4.检测到循环依赖

四、通过Field属性注入

  • 1.如@Autowired、@Resource注解
  • 2.控制了对象的外部可见性,不被spring容器托管的对象无法自动注入
  • 3.不能被检测出是否出现循环依赖
  • 4.被final修饰的属性,无法赋值

五、代码示例

5.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 {@Overridepublic String test() {return "test";}
}
5.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;@Autowiredpublic void setTestService(TestService testService){this.testService = testService;}@GetMapping("/get")public String test(){return testService.test();}
}
5.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 {@Autowiredprivate TestService testService;@GetMapping("/get")public String test(){return testService.test();}
}