© 版权声明:本文为博主原创文章,转载请注明出处

@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注解实现的更多相关文章

  1. Spring学习七----------Bean的配置之自动装配

    © 版权声明:本文为博主原创文章,转载请注明出处 Bean的自动装配(Autowiring) no:不启用自动装配,此时需要手动注入.参考:Spring学习三----------注入方式 defaul ...

  2. Spring学习九----------Bean的配置之Bean的定义及作用域的注解实现

    © 版权声明:本文为博主原创文章,转载请注明出处 Spring Bean常用注解 @Component:通常注解,可用于任何Bean @Repository:通常用于注解DAO层,即持久层 @Serv ...

  3. Spring学习十一----------Bean的配置之基于Java的容器注解@Bean

    © 版权声明:本文为博主原创文章,转载请注明出处 @Bean -@Bean标识一个用于配置和初始化一个由SpringIOC容器管理的新对象的方法,类似于XML配置文件的<bean/> -可 ...

  4. Spring学习五----------Bean的配置之Bean的生命周期

    © 版权声明:本文为博主原创文章,转载请注明出处 Bean的生命周期 1.定义 2.初始化 3.使用 4.销毁 初始化和销毁的三种方式 1.实现org.springframework.beans.fa ...

  5. Spring学习八----------Bean的配置之Resources

    © 版权声明:本文为博主原创文章,转载请注明出处 Resources 针对于资源文件的统一接口 -UrlResource:URL对应的资源,根据一个URL地址即可创建 -ClassPathResour ...

  6. spring学习六----------Bean的配置之Aware接口

    © 版权声明:本文为博主原创文章,转载请注明出处 Aware Spring提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化后,可以获取相应的资源 通过Aware接口,可以对S ...

  7. Spring学习四----------Bean的配置之Bean的配置项及作用域

    © 版权声明:本文为博主原创文章,转载请注明出处 Bean的作用域(每个作用域都是在同一个Bean容器中) 1.singleton:单例,指一个Bean容器中只存在一份(默认) 2.prototype ...

  8. spring 学习之 bean 的注入方式 property和constructor-arg的使用方式

    spring 学习之 bean 的注入方式 property和constructor-arg的使用方式. bean的注入方式: property 注入是: 通过setxx方法注入. construct ...

  9. Spring学习(十九)----- Spring的五种事务配置详解

    前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...

随机推荐

  1. How to use rowspan and colspan in tbody using datatable.js?

    https://stackoverflow.com/questions/27290693/how-to-use-rowspan-and-colspan-in-tbody-using-datatable ...

  2. HDU2767 Proving Equivalences

    Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission( ...

  3. 微信公众平台开发(71)OAuth2.0网页授权-摘抄

      微信公众平台开发 OAuth2.0网页授权认证 网页授权获取用户基本信息 作者:方倍工作室 微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友 ...

  4. 九、 Java程序初始化的顺序(二)

    之前的一篇博客里我写了关于在一个类中的程序初始化顺序,但是在Java的面向对象里,类之间还存在着继承的关系.所以关于程序的初始化顺序,我们可以再细划分为:父类静态变量,父类的静态代码块,父类构造器,父 ...

  5. HDU4757 Tree(可持久化Trie)

    写过可持久化线段树,但是从来没写过可持久化的Trie,今天补一补. 题目就是典型的给你一个数x,和一个数集,问x和里面的某个数xor起来的最大值是多少. 最原始的是数集是固定的,只需要对数集按照高到低 ...

  6. hdu 4519(数学题)

    郑厂长系列故事——体检 Time Limit: 500/200 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Total S ...

  7. LeetCode OJ--Combination Sum **

    https://oj.leetcode.com/problems/combination-sum/ 给一列数,3 2 1 3 3 8 7 9 ,每个数可以重复多次,给target 7, 问可以加起来得 ...

  8. 10.1综合强化刷题 Day3 afternoon

    竞赛时间:????年??月??日??:??-??:?? 题目名称 a b c 名称 a b c 输入 a.in b.in c.in 输出 a.out b.out c.out 每个测试点时限 1s 1s ...

  9. Docking For WPF–AvalonDock

    桌面程序的应用,不可避免的就会用到大量的布局控件,之前的一个项目也想过去做类似于Visual Studio的那种灵活的布局控件,也就是界面上的控件能够实现拖拽放置.隐藏.窗口化等一系列的操作,但由于开 ...

  10. nginx phase handler的原理和选择

    nginx phase handler的原理和选择 PHASE HANDLER的种类 nginx在接收并解析完请求行.请求头之后.就会依次调用各个phase handler. phase handle ...