Spring学习十----------Bean的配置之Autowired注解实现
© 版权声明:本文为博主原创文章,转载请注明出处
@Required
-@Required注解适用于bean属性的setter方法
-这个注解仅仅表示,受影响的bean属性必须在配置时被填充,通过在bean定义或通过自动装配一个明确的属性值
@Autowired
-可以将@Autowired注解为“传统”的setter方法
-可用于构造器或成员变量
-默认情况下,如果因找不到合适的bean将会导致autowiring失败跑出异常,可通过@Autowired(required=false)避免
-每个类只能有一个构造器被标记为required=true
-@Autowired的必要属性,建议使用@Required注解
-可以通过添加注解给需要该类型的数组的字段或方法,以提供ApplicationContext中所有特定类型的bean
-可以用于装配key为String的Map
-如果希望数组有序,可以让bean实现org.springframework.core.Ordered接口或使用@Order注解
-@Autowired是由Spring BeanPostProcessor处理的,所以不能再自己的BeanPostProcessor或BeanFactoryPostProcessor类型应用这些注解,这些类型必须通过XML或者Spring的 @Bean注解加载
@Qualifier
-按类型自动装配可能多个bean实例的情况,可以使用使用Spring的@Qualifier注解缩小范围(或指定唯一),也可以用于指定单独的构造器参数或方法参数
-可用于注解集合类型变量
@Resource
-通过其独特的名称来定义识别特定的目标(这是一个与所声明的类型无关的匹配过程)
-因语义差异,集合和Map类型的bean无法通过@Autowired来注入,因为没有类型匹配到这样的bean,为这些bean使用@Resource注解,通过唯一名称引用集合或Map的bean
实例:
1.项目结构
2.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springautowired</groupId>
<artifactId>Spring-Autowired</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Autowired Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<spring.version>4.3.8.RELEASE</spring.version>
</properties> <dependencies>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies> <build>
<finalName>Spring-Autowired</finalName>
</build> </project>
3.spring-autowired.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启包扫描将Bean加载到IOC容器中 -->
<context:component-scan base-package="org.springautowired.*"/> </beans>
4.BeanDao.java
package org.springautowired.dao; public interface BeanDao { public void save(String key); }
5.BeanDaoImpl.java
package org.springautowired.dao.impl; import org.springautowired.dao.BeanDao;
import org.springframework.stereotype.Repository; @Repository
public class BeanDaoImpl implements BeanDao { public void save(String key) { System.out.println("BeanDaoImpl保存成功,保存的数据为:" + key); } }
6.BeanService.java
package org.springautowired.service; public interface BeanService { public void save(String key); }
7.BeanServiceImpl.java
7.1 注解在成员变量上
package org.springautowired.service.impl; import org.springautowired.dao.BeanDao;
import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class BeanServiceImpl implements BeanService { @Autowired
private BeanDao beanDao; public void save(String key) { System.out.println("BeanServiceImpl接受参数:" + key);
beanDao.save(key); } }
7.2 注解在构造器上
package org.springautowired.service.impl; import org.springautowired.dao.BeanDao;
import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class BeanServiceImpl implements BeanService { private BeanDao beanDao; @Autowired
public BeanServiceImpl(BeanDao beanDao) {
this.beanDao = beanDao;
} public void save(String key) { System.out.println("BeanServiceImpl接受参数:" + key);
beanDao.save(key); } }
7.3 注解在setter方法上
package org.springautowired.service.impl; import org.springautowired.dao.BeanDao;
import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class BeanServiceImpl implements BeanService { private BeanDao beanDao; @Autowired
public void setBeanDao(BeanDao beanDao) {
this.beanDao = beanDao;
} public void save(String key) { System.out.println("BeanServiceImpl接受参数:" + key);
beanDao.save(key); } }
8.BeanController.java
8.1 注解在成员变量上
package org.springautowired.controller; import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; @Controller
public class BeanController { @Autowired
private BeanService beanService; public void save(String key) { System.out.println("BeanController开始执行插入方法");
beanService.save(key); } }
8.2 注解在构造器上
package org.springautowired.controller; import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; @Controller
public class BeanController { private BeanService beanService; @Autowired
public BeanController(BeanService beanService) {
this.beanService = beanService;
} public void save(String key) { System.out.println("BeanController开始执行插入方法");
beanService.save(key); } }
8.3 注解在setter方法上
package org.springautowired.controller; import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; @Controller
public class BeanController { private BeanService beanService; @Autowired
public void setBeanService(BeanService beanService) {
this.beanService = beanService;
} public void save(String key) { System.out.println("BeanController开始执行插入方法");
beanService.save(key); } }
9.BeanInterface.java
package org.springautowired.mutil; public interface BeanInterface { }
10.BeanInterfaceImpl1.java
package org.springautowired.mutil; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Order(2)
@Component
public class BeanInterfaceImpl1 implements BeanInterface { }
11.BeanInterfaceImpl2.java
package org.springautowired.mutil; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Order(1)
@Component
public class BeanInterfaceImpl2 implements BeanInterface { }
12.MultiBean.java
package org.springautowired.mutil; import java.util.List;
import java.util.Map; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; @Component
public class MultiBean { //使用@Autowired将所有实现BeanInterface接口的类放入list中,可用@Order指定顺序
@Autowired
private List<BeanInterface> list; //使用@Autowired将所有实现BeanInterface接口的类放入map中,bean ID作为key
@Autowired
private Map<String, BeanInterface> map; //使用@Qualifier缩小范围(指定唯一)
@Autowired
@Qualifier("beanInterfaceImpl2")
private BeanInterface beanInterface; //@Resource通过名字注入,与上一样
@Resource
private BeanInterface beanInterfaceImpl2; public void say() { if(list != null && list.size() > 0) {
System.out.println("list...");
for(BeanInterface bean: list) {
System.out.println(bean.getClass().getName());
}
}else{
System.out.println("List<BeanInterface> is null");
} if(map != null && map.size() > 0) {
System.out.println("map...");
for(String key: map.keySet()){
System.out.println(key + " " + map.get(key).getClass().getName());
}
}else{
System.out.println("Map<String, BeanInterface> is null");
} System.out.println("@Qualifier...");
if(beanInterface != null){
System.out.println(beanInterface.getClass().getName());
}else{
System.out.println("beanInterface is null");
} System.out.println("@Resource...");
if(beanInterfaceImpl2 != null){
System.out.println(beanInterfaceImpl2.getClass().getName());
}else{
System.out.println("beanInterfaceImpl2 is null");
} } }
13.TestBase.java
package org.springautowired.test; import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils; public class TestBase { private ClassPathXmlApplicationContext context;
private String springXmlPath; /**
* 无参构造器
*/
public TestBase() { } /**
* 含参构造器,初始化spring配置文件路径
*
* @param springXmlPath
* spring配置文件路径
*/
public TestBase(String springXmlPath) { this.springXmlPath = springXmlPath; } /**
* 初始化spring配置文件到IOC容器中
*/
@Before
public void before() { if(StringUtils.isEmpty(springXmlPath)){//默认spring配置文件路径
springXmlPath = "classpath:spring-*.xml";
}
context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]+"));
context.start(); } /**
* 销毁IOC容器
*/
@After
public void after() { if(context != null) {
context.destroy();
} } /**
* 通过bean ID获取bean对象
*
* @param beanId
* bean ID
* @return
*/
public Object getBean(String beanId) { return context.getBean(beanId); } }
14.TestSpringAutowired.java
package org.springautowired.test; import org.junit.Test;
import org.springautowired.controller.BeanController;
import org.springautowired.mutil.MultiBean; public class TestSpringAutowired extends TestBase { /**
* 构造函数初始化spring配置文件
*/
public TestSpringAutowired() { super("classpath:spring-autowired.xml"); } /**
* 测试@autowired在成员变量、构造器和setter方法上
*/
@Test
public void testAutoWired() { BeanController beanController = (BeanController) super.getBean("beanController");
beanController.save("test"); } /**
* 测试@Autowired装配指定类型的数组和key为String的Map
*/
@Test
public void testAutoWired2() { MultiBean bean = (MultiBean) super.getBean("multiBean");
bean.say(); } }
15.效果预览
参考:http://www.imooc.com/video/4031
http://www.imooc.com/video/4032
http://www.imooc.com/video/4160
Spring学习十----------Bean的配置之Autowired注解实现的更多相关文章
- Spring学习七----------Bean的配置之自动装配
© 版权声明:本文为博主原创文章,转载请注明出处 Bean的自动装配(Autowiring) no:不启用自动装配,此时需要手动注入.参考:Spring学习三----------注入方式 defaul ...
- Spring学习九----------Bean的配置之Bean的定义及作用域的注解实现
© 版权声明:本文为博主原创文章,转载请注明出处 Spring Bean常用注解 @Component:通常注解,可用于任何Bean @Repository:通常用于注解DAO层,即持久层 @Serv ...
- Spring学习十一----------Bean的配置之基于Java的容器注解@Bean
© 版权声明:本文为博主原创文章,转载请注明出处 @Bean -@Bean标识一个用于配置和初始化一个由SpringIOC容器管理的新对象的方法,类似于XML配置文件的<bean/> -可 ...
- Spring学习五----------Bean的配置之Bean的生命周期
© 版权声明:本文为博主原创文章,转载请注明出处 Bean的生命周期 1.定义 2.初始化 3.使用 4.销毁 初始化和销毁的三种方式 1.实现org.springframework.beans.fa ...
- Spring学习八----------Bean的配置之Resources
© 版权声明:本文为博主原创文章,转载请注明出处 Resources 针对于资源文件的统一接口 -UrlResource:URL对应的资源,根据一个URL地址即可创建 -ClassPathResour ...
- spring学习六----------Bean的配置之Aware接口
© 版权声明:本文为博主原创文章,转载请注明出处 Aware Spring提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化后,可以获取相应的资源 通过Aware接口,可以对S ...
- Spring学习四----------Bean的配置之Bean的配置项及作用域
© 版权声明:本文为博主原创文章,转载请注明出处 Bean的作用域(每个作用域都是在同一个Bean容器中) 1.singleton:单例,指一个Bean容器中只存在一份(默认) 2.prototype ...
- spring 学习之 bean 的注入方式 property和constructor-arg的使用方式
spring 学习之 bean 的注入方式 property和constructor-arg的使用方式. bean的注入方式: property 注入是: 通过setxx方法注入. construct ...
- Spring学习(十九)----- Spring的五种事务配置详解
前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...
随机推荐
- js复制到粘贴板
http://www.cnblogs.com/52fhy/p/5383813.html(移动端有兼容性问题) 要页面加载完直接绑定事件,否则第一次点击是绑定事件,第二次才触发事件 移动端需要设置tex ...
- git repo gerrit 的关系
Git作为一个版本控制工具,功能很强大,新建分支,切换分支都很快,小团队用Git就能很好地管理好了,但如果是Android系统如此庞大的工程呢,我们知道全套Android源码是很大很大的,目录结构也很 ...
- 更新yum 源
CentOS系统自带的更新源的速度实在是慢,为了让CentOS6使用速度更快的YUM更新源,可以选择163(网易)的更新源. 1.下载repo文件 wget http://mirrors.163.co ...
- 延迟加载技术 jquery lazyload
原文发布时间为:2011-01-17 -- 来源于本人的百度文章 [由搬家工具导入] 文章: http://www.appelsiini.net/projects/lazyload 下载地址:htt ...
- 使用CXF框架,发布webservice服务,并使用客户端远程访问webservice
使用CXF框架,发布webservice服务,并使用客户端远程访问webservice 1. CXF介绍 :soa的框架 * cxf 是 Celtrix (ESB框架)和 XFire(webs ...
- MySQL数据库”mysql SQL Error:1146,SQLState:42S02 “解决方法
项目在开发的时候在Mac平台下开发的,开发完了之后在LINUX环境上部署好之后,运行时MySQL数据库报错,提示为某个表不存在之类的错误信息,后来修改了MySQL的配置文件将大小写敏感去掉,问题解决. ...
- vim的语法高亮及配置文件说明
本文主要针对那些刚刚入门的菜鸟,老手请自动忽略,谢谢. 一.安装vim: sudo pacman -S vim 随后根据提示输入超级用户密码即可完成安装 二.配置自己的语法高亮文件,主要是修改-/.v ...
- CocoaPods Setting up CocoaPods master repo无反应时的处理
Setting up CocoaPods master repo,半天没有任何反应.原因无他,因为那堵墙阻挡了cocoapods.org...gitcafe和oschina都是国内的服务器,可以用它们 ...
- 16Aspx.com-PHP企业整站源码 景观石材大理石类织梦模板 含手机移动端 完整源码 APP+PC
=============================================== 源码站长资源交易专业网-商业源码下载,VIP源码,程序交易,毕业设计交易,站长交易|- 16aspx.c ...
- Gym 101064 D Black Hills golden jewels 【二分套二分/给定一个序列,从序列中任意取两个数形成一个和,两个数不可相同,要求求出第k小的组合】
D. Black Hills golden jewels time limit per test 2 seconds memory limit per test 256 megabytes input ...