文章目录
前言
项目中一般都会使用@Value和@Autowired进行依赖注入,但是到了该怎么用才能注入成功,或者到底该怎么用才合适呢?
@Value
可以写在实例变量、只有一个参数的实例方法(包括构造方法)、构造方法的参数上。spring在4.x版本后就推荐使用构造方法进行注入。
实例变量注入
@RequestMapping("/sys")
@RestController
public class SysController {
@Value("${port:8080}")
private /*final*/ Integer port;
}
只有一个参数的实例方法(包括构造方法)注入
@RequestMapping("/sys")
@RestController
public class SysController {
private /*final*/ Integer port;
@Value("${port:8080}")
public void setPort(Integer port) {
this.port = port;
}
}
构造方法的参数注入
@RequestMapping("/sys")
@RestController
public class SysController {
private final Integer port;
public SystemController (@Value("${port:8080}") Integer port){
this.port = port;
}
// pxl 若构造方法只有一个要注入的参数,也可以将@Value放在该构造方法上
/*
@Value("${port:8080}")
public SysController(Integer port) {
this.port = port;
}*/
}
注意:不能将@Value加在普通实例方法的参数上,这样无法注入。
@Autowired
可以写在实例变量、有一个或多个参数的实例方法(包括构造方法)、构造方法的参数上。spring在4.x版本后就推荐使用构造方法进行注入。
实例变量注入
@RequestMapping("/sys")
@RestController
public class SysController {
@Autowired
private /*final*/ SysService sysService;
@Autowired
private /*final*/ UserService userService;
}
有一个或多个参数的实例方法(包括构造方法)注入
@RequestMapping("/sys")
@RestController
public class SysController {
private /*final*/ SysService sysService;
private /*final*/ UserService userService;
@Autowired
public void setSysService(SysService sysService) {
this.sysService = sysService;
}
@Autowired
public void setServices(SysService sysService, UserService userService) {
this.sysService = sysService;
this.userService = userService;
}
}
构造方法的参数注入
@RequestMapping("/sys")
@RestController
public class SysController {
private final SysService sysService;
private final UserService userService;
// pxl
public SysController(@Autowired SysService sysService, @Autowired UserService userService) {
this.sysService = sysService;
this.userService = userService;
}
}
- 注:在Spring4.3+之后,如果目标bean仅仅定义了一个构造方法,就不必指定@Autowired注解了,spring会自动为你注入属性;配合lombok的@RequiredArgsConstructor使用体验很好。
@RequestMapping("/sys")
@RestController
public class SysController {
private final SysService sysService;
private final UserService userService;
// 在Spring4.3+可以这样写,亲测在Spring4.0.6这样会抛异常org.springframework.beans.factory.BeanCreationException: Could not autowire field,即每个属性上都要加@Autowired或在构造方法上加@Autowired
public SysController(SysService sysService, UserService userService) {
this.sysService = sysService;
this.userService = userService;
}
}
- 注:更多情况请参考深度分析Spring中的构造器注入
@Value与@Autowired混合使用
执行到有@Autowired的构造方法时:
执行到有@PostConstruct的方法时:
@value注入static静态变量
参考我的另一篇文章spring中使用@value注入static静态变量