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的事务配置只要把思路理清,还是比较好掌握的. ...
随机推荐
- vue父组件向子组件传递数据
父组件 <template> <div id="app"> <v-header :childseller="fatherseller&quo ...
- 【CF1073C】Vasya and Robot(二分,构造)
题意:给定长为n的机器人行走路线,每个字符代表上下左右走,可以更改将一些字符改成另外三个字符,定义花费为更改的下标max-min+1, 问从(0,0)走到(X,Y)的最小花费,无解输出-1 n< ...
- Linux Mint---安装篇
先前接触过Debian6,埋头折腾已经是好几年前的事情了,后来就放下了,现在工作之余时间比较多,正好debian8.1出来了,于是乎装了个debian用,结果,自己其实还是一个菜蛋而已,连软件源怎么设 ...
- mdev的基本工作原理【转】
转自:http://www.cnblogs.com/hnrainll/archive/2011/06/10/2077435.html 分析过mdev(udev的BusyBox简化版)源码的都知道mde ...
- jquery -----简单分页
<!DOCTYPE html> <head> <title>无标题页</title> <script src="javsscript/j ...
- Android修改包名的方法,简单粗暴。
几分钟之内,简单粗暴的修改包名! 序:Android的新手玩家可能对修改包名这件事情很是烦恼,我这里给出一个最快的修改包名的方法,简单粗暴,喜欢的可以收藏一下. 开始修改 第一步:修改自己app mo ...
- 洛谷 P1464 Function【动态规划(递推)/记忆化搜索(递归)】
题目描述 对于一个递归函数w(a,b,c) 如果a<=0 or b<=0 or c<=0就返回值1. 如果a>20 or b>20 or c>20就返回w(20,2 ...
- memcached的内存管理与删除机制
memcached的内存管理与删除机制 简介 注意:Memcache最大的value也只能是1M的空间,超过1M的数据无法保存(修改memcache源代码). 注意:内存碎片化永远都存在,只是哪一 ...
- kafka消费者客户端
Kafka消费者 1.1 消费者与消费者组 消费者与消费者组之间的关系 每一个消费者都隶属于某一个消费者组,一个消费者组可以包含一个或多个消费者,每一条消息只会被消费者组中的某一个消费者所消费.不 ...
- inux 下的/etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc 文件的作用
/etc/bashrc:为每一个运行bash shell的用户执行此文件.当bash shell被打开时,该文件被读取. ~/.bash_profile:每个用户都可使用该文件输入专用于自己使用的sh ...