SpringBoot注入Bean的几种方式(最佳实战)

目录
方法一:@RequiredArgsConstructor(最佳实战)
/**
* @author edevp
*/
@Service
public class OrderService
...
...
@RequiredArgsConstructor
public class OrderController {
private final OrderService orderService;
}
等同于
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
}
方法二:@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OrderController {
private final OrderService orderService;
}
方法三:@Autowired注解
@Autowired注解是Spring提供,只按照byType进行注入。@Autowired如果想要按照byName方式需要加@Qualifier,Qualifier意思是合格者,一般跟Autowired配合使用,需要指定一个bean的名称,通过bean名称就能找到需要装配的bean。
//定义一个服务,添加@Service交给Spring Boot管理
@Service
public class Service1 {
}
//在另一个Service中需要依赖,使用方法如下。
@Service
public class Service2 {
@Autowired
private Service1 service1;
}
方法二:@Resource注解
@Resource注解是Java标准库提供。默认采用byName方式进行注入,如果找不到则使用byType。可通过注解参数进行改变。比起Autowired好处在于跟Spring的耦合度没有那么高。
//定义一个服务,添加@Service交给Spring Boot管理
@Service
public class Service1 {
}
//在另一个Service中需要依赖,使用方法如下。
@Service
public class Service2 {
@Resource
private Service1 service1;
}