注解Annotation的IoC:从@Autowired到@Component
注解Annotation的IoC:从@Autowired到@Component
2017-01-23
目录
1 什么是注解
2 不使用注解示例
2.1 com.springioc.animal.Monkey
2.2 com.springioc.animal.Tiger
2.3 com.springioc.bean.Zoo
2.4 com.springioc.main.AppMain
2.5 Beans.xml
3 使用注解@Autowired示例
3.1对成员变量使用@Autowired
3.2 将 @Autowired 注解标注在 Setter 方法上
3.3 将 @Autowired 注解标注在构造函数上
3.4 @Autowired(required = false)
4 使用注解@Resource示例
5 使用注解@Component示例
5.1示例
5.2 component scan过滤方式
5.3 @Component、@Controller、@Repository,@Service
参考
1 什么是注解
传统的Spring做法是使用.xml文件来对bean进行注入。
注解配置相对于 XML 配置具有很多的优势:
- 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用 JPA 注解配置 ORM 映射时,我们就不需要指定 PO 的属性名、类型等信息,如果关系表字段和 PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过 Java 反射机制获取。
- 注解和 Java 代码位于一个文件中,而 XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和 Java 代码放在一起,有助于增强程序的内聚性。而采用独立的 XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
2 不使用注解示例
目录结构如下:
2.1 com.springioc.animal.Monkey
package com.springioc.animal; public class Monkey {
private String monkeyName = "LaoEr"; public String toString() {
return "MonkeyName:" + monkeyName;
}
}
2.2 com.springioc.animal.Tiger
package com.springioc.animal; public class Tiger {
private String tigerName = "LaoDa"; public String toString() {
return "TigerName:" + tigerName;
}
}
2.3 com.springioc.bean.Zoo
package com.springioc.bean; import com.springioc.animal.*; public class Zoo {
private Tiger tiger;
private Monkey monkey; public void setTiger(Tiger tiger) {
this.tiger = tiger;
} public void setMonkey(Monkey monkey) {
this.monkey = monkey;
} public Tiger getTiger() {
return tiger;
} public Monkey getMonkey() {
return monkey;
} public String toString() {
return tiger + "\n" + monkey;
}
}
2.4 com.springioc.main.AppMain
package com.springioc.main; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.springioc.bean.Zoo; public class AppMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Zoo zoo = (Zoo) context.getBean("zoo");
System.out.println(zoo.toString());
}
}
2.5 Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"
default-autowire="byType"> <bean id="zoo" class="com.springioc.bean.Zoo" >
<property name="tiger" ref="tiger" />
<property name="monkey" ref="monkey" />
</bean> <bean id="tiger" class="com.springioc.animal.Tiger" />
<bean id="monkey" class="com.springioc.animal.Monkey" />
</beans>
运行结果:
TigerName:LaoDa
MonkeyName:LaoEr
3 使用注解@Autowired示例
Spring 2.5 引入了 @Autowired 注解,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
3.1 对成员变量使用@Autowired
对Zoo类的两个变量tiger和monkey使用注解Autowired,可以删除Set方法
package com.springioc.bean; import org.springframework.beans.factory.annotation.Autowired; import com.springioc.animal.*; public class Zoo {
@Autowired
private Tiger tiger;
@Autowired
private Monkey monkey;
public String toString() {
return tiger + "\n" + monkey;
}
}
Beans.xml
Beans.xml文件中删除zoo的property,增加(注册)AutowiredAnnotationBeanPostProcessor处理器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- context:component-scan base-package="com.springioc.bean" / -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="zoo" class="com.springioc.bean.Zoo" >
</bean> <bean id="tiger" class="com.springioc.animal.Tiger" />
<bean id="monkey" class="com.springioc.animal.Monkey" />
</beans>
解读:
当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有@Autowired 注解时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。
按照上面的配置,Spring 将直接采用 Java 反射机制对 Zoo 中的 tiger 和 monkey 这两个私有成员变量进行自动注入。所以对成员变量使用 @Autowired 后,您大可将它们的 setter 方法(setTiger() 和 setOMonkey())从 Zoo 中删除。
注意:
Beans.xml文件中,可以用<context:component-scan base-package="com.springioc.bean" /> 替换 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 。
因为<context:component-scan>会默认激活<context:annotation-config>功能的。而<context:annotation-config>会隐式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及equiredAnnotationBeanPostProcessor 这 4 个 BeanPostProcessor。
3.2 将 @Autowired 注解标注在 Setter 方法上
package com.springioc.bean; import org.springframework.beans.factory.annotation.Autowired; import com.springioc.animal.*; public class Zoo { private Tiger tiger;
private Monkey monkey; @Autowired
public void setTiger(Tiger tiger) {
this.tiger = tiger;
} @Autowired
public void setMonkey(Monkey monkey) {
this.monkey = monkey;
} public Tiger getTiger() {
return tiger;
} public Monkey getMonkey() {
return monkey;
} public String toString() {
return tiger + "\n" + monkey;
}
}
3.3 将 @Autowired 注解标注在构造函数上
package com.springioc.bean; import org.springframework.beans.factory.annotation.Autowired; import com.springioc.animal.*; public class Zoo { private Tiger tiger;
private Monkey monkey; public void setTiger(Tiger tiger) {
this.tiger = tiger;
} public void setMonkey(Monkey monkey) {
this.monkey = monkey;
} public Tiger getTiger() {
return tiger;
} public Monkey getMonkey() {
return monkey;
} @Autowired
public Zoo(Tiger tiger, Monkey monkey) {
this.tiger = tiger;
this.monkey = monkey;
} public String toString() {
return tiger + "\n" + monkey;
}
}
3.4 @Autowired(required = false)
当候选 Bean 数目不为 1 时的应对方法:@Autowired(required = false)
在默认情况下使用 @Autowired 注解进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean。我们可以来做一个实验:
Bean.xml文件中,注解掉Monkey
<!-- bean id="monkey" class="com.springioc.animal.Monkey" / -->
由于 Monkey Bean 被注解掉了,所以 Spring 容器中将没有类型为 Monkey的 Bean 了,而 Zoo 的 Monkey属性标注了 @Autowired,当启动 Spring 容器时,异常就产生了。
当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错。如下代码:
对Zoo类中setter注解@Autowired(required = false)
@Autowired(required = false)
public void setMonkey(Monkey monkey) {
this.monkey = monkey;
}
运行结果如下:
TigerName:LaoDa
null
4 使用注解@Resource示例
Spring 不但支持自己定义的 @Autowired
的注解,还支持几个由 JSR-250 规范定义的注解,它们分别是 @Resource
、@PostConstruct
以及 @PreDestroy
。
@Resource 的作用相当于 @Autowired,只不过 @Autowired 按 byType(就是按Bean的Class的类型)自动注入,面 @Resource 默认按 byName(就是通过Bean的id或者name) 自动注入罢了。
Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将 @Resource 注解的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。
Resource 注解类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中,因此在使用之前必须将其加入到项目的类库中。来看一个使用 @Resource 的例子:
@Resource
private Tiger tiger; @Resource(name="monkey1")
private Monkey monkey;
注意一般情况下,我们无需使用类似于 @Resource(type=Tiger.class) 的注解方式,因为 Bean 的类型信息可以通过 Java 反射从代码中获取。
要让 JSR-250 的注解生效,除了在 Bean 类中标注这些注解外,还需要在 Spring 容器中注册一个负责处理这些注解的BeanPostProcessor:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- context:component-scan base-package="com.springioc.bean" / -->
<!--bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/-->
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> <bean id="zoo" class="com.springioc.bean.Zoo" >
</bean> <bean id="tiger" class="com.springioc.animal.Tiger" />
<bean id="monkey1" class="com.springioc.animal.Monkey" />
<bean id="monkey2" class="com.springioc.animal.Monkey"/>
</beans>
5 使用注解@Component示例
虽然我们可以通过 @Autowired 或 @Resource 在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 <bean> 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过 @Autowired 或 @Resource 为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。
能否也通过注解定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的 @Component 注解就可以达到这个目标了。
5.1 示例
使用 @Component 注解的Monkey.java
仅需要在类定义处,使用 @Component
注解就可以将一个类定义了 Spring 容器中的 Bean
package com.springioc.animal; import org.springframework.stereotype.Component; @Component
public class Monkey {
private String monkeyName = "LaoEr"; public String toString() {
return "MonkeyName:" + monkeyName;
}
}
使用 @Component 注解的 Tiger.java
package com.springioc.animal; import org.springframework.stereotype.Component; @Component
public class Tiger {
private String tigerName = "LaoDa"; public String toString() {
return "TigerName:" + tigerName;
}
}
使用 @Component 注解的 Zoo.java
@Component("zoo")
public class Zoo { @Autowired
private Tiger tiger; @Autowired
private Monkey monkey;
...
}
@Component 有一个可选的入参,用于指定 Bean 的名称,在 Zoo 中,我们就将 Bean 名称定义为“zoo”(默认名称也是“zoo”,第一个字母变小写)。一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。
在使用 @Component 注解后,Spring 容器必须启用类扫描机制以启用注解驱动 Bean 定义和注解驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,在Beans.xml添加如下配置:
<context:component-scan base-package="com.springioc.bean" />
这里,所有通过 <bean> 元素定义 Bean 的配置内容已经被移除,仅需要添加一行 <context:component-scan/> 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注解形式存在罢了)。<context:component-scan/> 的 base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
5.2 component scan过滤方式
<context:component-scan/> 还允许定义过滤器将基包下的某些类纳入或排除。Spring 支持以下 5 种类型的过滤方式,通过下表说明:
Filter Type | Examples Expression | Description |
annotation | org.example.SomeAnnotation | 符合SomeAnnoation的target class |
assignable | org.example.SomeClass | 指定class或interface的全名 |
aspectj | org.example..*Service+ | AspectJ語法 |
regex | org\.example\.Default.* | Regelar Expression |
custom | org.example.MyTypeFilter | Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter |
5.3 @Component、@Controller、@Repository,@Service
@Component,@Controller,@Repository,@Service,这四个注解都在org.springframework.stereotype包下面,后面3个都属于@Component。
可以理解为@Component是@Controller,@Repository,@Service的基类。
- @Component是用来标记任何被Spring管理的组件。
- @Controller用来标记presentation层(比如web controller)。
- @Repository用来标记persistence层(比如DAO)。
- @Service用来标记service层。
参考
[1] 注解Annotation的IoC (@Autowired @Component )
[2] [Spring Framework]学习笔记--@Component等stereotype的基础
[3] Spring5:@Autowired注解、@Resource注解和@Service注解
注解Annotation的IoC:从@Autowired到@Component的更多相关文章
- SpringMVC 用注解Annotation驱动的IoC功能@Autowired @Component
转载自:http://blog.csdn.net/lufeng20/article/details/7598564 本文分为三个部分:概述.使用注解进行属性注入.使用注解进行Bean的自动定义. 一, ...
- JavaEE互联网轻量级框架整合开发(书籍)阅读笔记(10):通过注解(annotation)装配Bean之(@Configguration、@Component、@Value、@ComponentScan、@Autowired、@Primary、@Qualifier、@Bean)
一.通过注解(annotation)装配Bean 通过之前的学习,我们已经知道如何使用XML装配Bean,但是更多的时候已经不再推荐使用XML的方式去装配Bean,更多的时候会考虑注解(annotat ...
- Spring Boot@Component注解下的类无法@Autowired的问题
title: Spring Boot@Component注解下的类无法@Autowired的问题 date: 2019-06-26 08:30:03 categories: Spring Boot t ...
- 注解 @Resource与@Autowired与@Component的使用
在java代码中使用@Autowired或@Resource注解方式进行装配,这两个注解的区别是:@Autowired 默认按类型装配,@Resource默认按名称装配,当找不到与名称匹配的bean才 ...
- Spring 使用纯注解方式完成IoC
目录 创建一个简单的Person类 使用xml方式配置Spring容器并获取bean的过程 创建xml配置文件 进行测试 使用纯注解方式配置Spring容器并获取bean的过程 创建spring配置类 ...
- Spring框架context的注解管理方法之二 使用注解注入基本类型和对象属性 注解annotation和配置文件混合使用(半注解)
首先还是xml的配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...
- Spring中注解方式实现IOC和AOP
1.IOC注解 1.1 IOC和DI的注解 IOC: @Component:实现Bean组件的定义 @Repository:用于标注DAO类,功能与@Component作用相当 @Service:用 ...
- Bean 注解(Annotation)配置(3)- 依赖注入配置
Spring 系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of ...
- Bean 注解(Annotation)配置(2)- Bean作用域与生命周期回调方法配置
Spring 系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of ...
随机推荐
- webpack 安装以及使用
1.安装webpack 全局安装代码: npm install -g webpack 2.项目中使用webpack (1)进入项目目录 cd C:\Users\dell\Documents\HBuil ...
- python第三方包的windows安装文件exe格式
今天弄了一上午的python-ldap,发现要么安装vc,要么用其他比较麻烦的方法,都比较麻烦.幸好找到这个地址: http://www.lfd.uci.edu/~gohlke/pythonlibs/ ...
- 微信小程序--搜索关键词高亮
代码地址如下:http://www.demodashi.com/demo/14249.html 一.前期准备工作 软件环境:微信开发者工具 官方下载地址:https://mp.weixin.qq.co ...
- android-使用环信SDK开发即时通信功能及源代码下载
近期项目中集成即时聊天功能.挑来拣去,终于选择环信SDK来进行开发,选择环信的主要原因是接口方便.简洁.说明文档清楚易懂.文档有android.ios.和后台server端.还是非常全的. 环信官网: ...
- servlet下根据相对路径找资源
1.在web项目中如果直接添加一个资源,那么相对路径相对的是tomcat的bin目录. 2.在包中直接指定资源,那么可以使用以下的相对路径直接获取资源: InputStream in = this.g ...
- Web前端开发笔试&面试_02(others)
AL>> 1.CSS 3 如何实现旋转图片? 答:transform : rotate 2.写CSS 的工具? 答:LESS.SASS 3.JavaScript 倒计时? 答:setTim ...
- Windows下面安装和配置Solr 4.9(二)
将Solr和Tomcat结合: 1.在D盘下创建目录 D:\Demos\Solr 2.解压solr-4.9.0文件,我这里下载的是这个4.9版本,将example文件夹下的solr文件夹中的所有文件( ...
- ios 中的tintColor
在iOS 7后,UIView新增加了一个tintColor属性,这个属性定义了一个非默认的着色颜色值,其值的设置会影响到以视图为根视图的整个视图层次结构.它主要是应用到诸如app图标.导航栏.按钮等一 ...
- c#基础之异常处理及自定义异常 从SQLServer转储数据到MySQL
c#基础之异常处理及自定义异常 一.什么是c#中的异常? 异常是程序运行中发生的错误,异常处理是程序的一部分.c#中的异常类主要是直接或者间接的派生于 System.Exception类 ,也就是说S ...
- Android笔记(十)ListView
ListView是Android中最经常使用的控件之中的一个,也是最难用的控件. ListView的作用是展示大量的数据,只是ListView并非直接和数据打交道.而是通过适配器作为中间桥梁. 1.首 ...