栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Bean与依赖注入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Bean与依赖注入

怎么注册Bean组件呢?

开启注解扫描后,凡是使用以下三种注解标记的类会自动扫描到Spring容器中:

@Component

@Service

@Service 
public class BusinessServiceImpl implements BusinessService {

}

@Repository

@Repository 
public class DataServiceImpl implements DataService {

}

@Service常用于业务逻辑相关的Bean,@Repository常用于数据仓库相关的Bean

有了Bean,怎么配置依赖关系呢?

前面我们了解到,BusinessServiceImpl需要依赖DataServiceImpl的对象。因此,我们需要把DataServiceImpl的Bean对象注入到BusinessServiceImpl里面。

public class BusinessServiceImpl { 
      @Autowired 
      private DataService dataService;

}

只要将被依赖的Bean作为成员变量声明在依赖的Bean中,并使用@Autowired 注解进行标记,Spring会自动完成对象的注入。

 假设我们有这么一个DataService的实现,那么DataServiceImpl的对象会自动注入到BusinessServiceImpl中:

@Repository 
public class DataServiceImpl implements DataService { 
      public List retrieveData(User user) { 
             return Arrays.asList(new Data(10), new Data(20)); 
      } 
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/606370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号