Spring怎么使用注解进行引用类型的自动装
导读:本文共1606字符,通常情况下阅读需要5分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 一.案例分级简单解析:配置类替代以前的配置文件,实体类提供对象,业务类中有实体类的引用对象,在业务层中实现引用类的自动装配。二.各层代码及详细解析配置类:(关于配置类中两个注解的解释可以参考前面文章)packagecom.itheima.config;importorg.springframework.context.annotation.ComponentS... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。一.案例分级
简单解析:配置类替代以前的配置文件,实体类提供对象,业务类中有实体类的引用对象,在业务层中实现引用类的自动装配。
二.各层代码及详细解析
配置类:(关于配置类中两个注解的解释可以参考前面文章)
packagecom.itheima.config;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;@Configuration//设置为配置类@ComponentScan("com.itheima")//在com.otheima这个包下扫描bean对象publicclassSpringConfig{}
实体类BookDaoImpl:
packagecom.itheima.dao.impl;importcom.itheima.dao.BookDao;importorg.springframework.context.annotation.Scope;importorg.springframework.stereotype.Component;importorg.springframework.stereotype.Repository;@Repository//注解注册beanpublicclassBookDaoImplimplementsBookDao{publicvoidsave(){System.out.println("bookdaosave...");}}
实体接口BookDao:
packagecom.itheima.dao;publicinterfaceBookDao{publicvoidsave();}
业务类BookServiceImol:
packagecom.itheima.service.impl;importcom.itheima.dao.BookDao;importcom.itheima.service.BookService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassBookServiceImolimplementsBookService{@AutowiredprivateBookDaobookDao;publicvoidsave(){System.out.println("bookservicesave....");bookDao.save();}}
@Service:注册bean对象,在执行类中使用getBean()方法获取.
@Autowired:进行自动装配,如果没有此句话,将会出现以下错误运行结果:
业务接口BookService:
packagecom.itheima.service;publicinterfaceBookService{publicvoidsave();}
执行类App3:
packagecom.itheima;importcom.itheima.config.SpringConfig;importcom.itheima.dao.BookDao;importcom.itheima.service.BookService;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;importjava.awt.print.Book;publicclassApp3{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextctx=newAnnotationConfigApplicationContext(SpringConfig.class);BookServiceservice=ctx.getBean(BookService.class);service.save();}}
三.自动装配成功正确执行结果
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
Spring怎么使用注解进行引用类型的自动装的详细内容,希望对您有所帮助,信息来源于网络。