Springboot:@Service注解作用 以及 当有多个Impl时如何知道注入的是哪个Impl

学习自:

(37条消息) @Service注解怎么使用?@Service注解的用法__花野的博客-CSDN博客_@service注解

(39条消息) Spring中 如果该Service有多个实现类,它怎么知道该注入哪个ServiceImpl类?_蔡定努的博客-CSDN博客

 

1、@Service注解的作用

用于Service实现类前(注意是实现类Impl,而非接口),标记当前类是一个Service类,加上该注解会自动将当前类注入到Spring容器中,不需要在xml文件中定义Bean了。

其作用和@Component、@bean、@Controller、@Repository一样。

@Service("courseDAO")
public class CourseDAOImpl implements CourseDAO{
        ...    
}

在其他类中注入调用:

@Autowried
private CourseDAOImpl  courseDAOImpl;

2、如果一个Service接口有多个实现类Impl,那注入时怎么知道注入的是哪一个呢?

答案是为Impl命名

通过@Service传入名称,这样就为每个Impl定了一个名称,默认情况下的名称就是首字母小写的Service接口名

命名

如果要命名,写法为:

@Service("名称")
public class XxxServiceImpl implements XxxService{
  ...
}

注入

在Controller中注入Service时,通过说明名称来指定注入哪个Service:

//注入方式1
@Autowired
@Qualifier("名称")
private XxxService xxxService;

//注入方式2
@Resource(name="名称")
private XxxService xxxService;

这样就可以使用指定的Service了。

 

posted @ 2022-07-17 10:28  ShineLe  阅读(5356)  评论(0编辑  收藏  举报