JDK1.8
Java开发IDE
上一篇文章小编介绍了Spring5的编码风格有3中分别是:Schema-based、Annotation-based和Java-based。小编喜欢使用Annotation-based和Java-based配合使用,引入Spring依赖,小编的项目结构如下图所示:
新建“SpringConfig”,该文件作为Spring的配置文件,小编的“SpringConfig”文件位于“org.whays.spring.config”。如下图所示:
新建“IndexDao”接口,作为我们的测试Dao,小编的“IndexDao”位于“org.whays.spring.ioc”。如下图所示:
新建“IndexDaoImpl1”实现“IndexDao”,并在“IndexDaoImpl1”加入“@Repository”注解如下图所示:
新建“IndexDaoImpl2”实现“IndexDao”,并在“IndexDaoImpl2”加入“@Repository”注解如下图所示:
新建“IndexService”,并依赖“IndexDao”,在属性(Field) indexDao加上“@Autowired”注解,并在“IndexService”加上“@Service”注解。如下图所示:
此时我们通过“AnnotationConfigApplicationContext”获取“IndexService”实例将会报错。AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); IndexService service = (IndexService)context.getBean('indexService'); service .callService();如下图所示:
(注:通过以上代码我们知道@Autowired根据byType注入) 我们接下来将IndexService 中的依赖indexDao属性(Field)修改为indexDaoImpl1。如下图所示:
再次通过“AnnotationConfigApplicationContext”获取“IndexService”实例。AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);IndexService service = (IndexService)context.getBean('indexService');service .callService();如下图所示:
(根据以上运行结果得知,@Autowired默认根据byType进行注入,但是在根据byType未获得实例时会根据byName进行注入,byName为属性名(Field))。如下图所示:
修改IndexService 中依赖属性“indexDaoImpl1”注解@Autowired为“@Resource”。如下图所示:
再次通过“AnnotationConfigApplicationContext”获取“IndexService”实例。AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);IndexService service = (IndexService)context.getBean('indexService');service .callService();如下图所示:
通过以上运行结果,我们知道@Resource默认通过byName(属性名)进行注入。我们将“IndexDaoImpl1”的注解“@Repository”去掉。如下图所示:
将IndexService 中的依赖indexDaoImpl1属性(Field)修改为indexDao。如下图所示:
再次通过“AnnotationConfigApplicationContext”获取“IndexService”实例。AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);IndexService service = (IndexService)context.getBean('indexService');service .callService();如下图所示:
总结:@Autowired 默认通过byType方式进行依赖注入,如果byType没有获得实例将通过byName(FieldName)方式进行依赖注入。@Resource 默认通过byName(FieldName而非SetName)方式进行依赖注入,如果byName没有获得实例则通过byType方式进行依赖注入。以上的总结是基于Annotation-based和Java-based配合下的情况,而非Schema-based使用总结。
配合Annotation-based和Java-based
byName非bySetName(set方法名)