组件装配:

<context:component-sacan> 元素还会自动注册 AutowiredAnnotationBeanPostProcesser 实例 , 该实例可以自动装配具有 @Autowired 和 @Resource 、 @Inject 注解的属性。

使用 @Autowired 自动装配 Bean:

@Autowired 注解自动装配具有兼容类型的单个 Bean 属性:

  • 构造器 , 普通字段(即使是非 public) , 一切具有参数的方法都可以用 @Autowired 注解。
  • 默认情况下 , 所有使用 @Autowired 注解的属性都需要被设置。当 Spring 找不到匹配的 bean 装配属性时 , 会抛出异常 , 若某一属性允许不被设置 , 可以设置 @Autowired 注解的 required 属性为 false。
  • 默认情况下 , 当 IOC 容器里存在多个类型兼容的 bean 时 , 通过类型的自动装配将无法工作 , 此时可以在 @Qualifier 注解里提供 bean 的名称。Spring 允许对方法的入参标注 @Qualifiter 已指定注入 bean 的名称。或在需要自动装配的注解中通过 value 属性值标识组件的名称。
  • @Autowired 注解也可以应用在数组类型的属性上 , 此时 Spring 将会把所有匹配的 bean 进行自动装配。
  • @Autowired 注解也可以应用在集合属性上 , 此时 Spring 读取该集合的类型信息 , 然后自动装配所有与之兼容的 bean。
  • @Autowired 注解用在 java.util.Map 上时 , 若该 Map 的键值为 String , 那么 Spring 将自动装配与之 Map 值类型兼容的 bean , 此时 bean 的名称作为键值。
 <?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"> <!-- 指定 Spring IOC 容器扫描的包 -->
<context:component-scan base-package="com.itdjx.spring.annotation"/> </beans>
 package com.itdjx.spring.annotation.controller;

 import com.itdjx.spring.annotation.service.UserService;
import org.springframework.stereotype.Controller; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:28
*/
@Controller
public class UserController {
private UserService userService; public void execute() {
System.out.println("I am UserController's execute method...");
userService.add();
}
}
 package com.itdjx.spring.annotation.service;

 import com.itdjx.spring.annotation.repository.UserRepository;
import org.springframework.stereotype.Service; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:26
*/
@Service
public class UserService { private UserRepository userRepository; public void add() {
System.out.println("I am UserService's add method...");
userRepository.sava();
}
}
 package com.itdjx.spring.annotation.repository;

 /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:23
*/
public interface UserRepository { void sava(); }
 package com.itdjx.spring.annotation.repository;

 import org.springframework.stereotype.Repository;

 /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:24
*/
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository { @Override
public void sava() {
System.out.println("I am UserRepositoryImpl's sava method...");
}
}
 package com.itdjx.spring.annotation;

 import com.itdjx.spring.annotation.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:34
*/
public class Main { public static void main(String[] args) { ApplicationContext cxt = new ClassPathXmlApplicationContext("beans-annotation.xml");
UserController userController = (UserController) cxt.getBean("userController");
userController.execute(); }
}

控制台输出:

Exception in thread "main" java.lang.NullPointerException
at com.itdjx.spring.annotation.controller.UserController.execute(UserController.java:16)
at com.itdjx.spring.annotation.Main.main(Main.java:17)

原因:IOC 容器中虽然每个 bean 节点都存在 , 但是没有引入到需要引入的 bean 节点中 , 需要将需要引入的 bean 节点引入相应的 bean 节点中。

 package com.itdjx.spring.annotation.controller;

 import com.itdjx.spring.annotation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:28
*/
@Controller
public class UserController {
@Autowired
private UserService userService; public void execute() {
System.out.println("I am UserController's execute method...");
userService.add();
}
}
 package com.itdjx.spring.annotation.service;

 import com.itdjx.spring.annotation.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:26
*/
@Service
public class UserService { @Autowired
private UserRepository userRepository; public void add() {
System.out.println("I am UserService's add method...");
userRepository.sava();
}
}

控制台输出:

I am UserController's execute method...
I am UserService's add method...
I am UserRepositoryImpl's sava method...

假如我们将 IOC 容器中不存在的 bean 节点引入到 bean 节点中 , 会出现什么状况呢?

 package com.itdjx.spring.annotation;

 /**
* @author Wáng Chéng Dá
* @create 2017-03-03 8:44
*/ public class TestObject {
}
 package com.itdjx.spring.annotation.repository;

 import com.itdjx.spring.annotation.TestObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:24
*/
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository { @Autowired
private TestObject testObject;
@Override
public void sava() {
System.out.println("I am UserRepositoryImpl's sava method...");
System.out.println(testObject);
}
}

控制台输出:

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRepository': Unsatisfied dependency expressed through field 'testObject'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.annotation.TestObject' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRepository': Unsatisfied dependency expressed through field 'testObject'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.annotation.TestObject' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.itdjx.spring.annotation.Main.main(Main.java:15)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRepository': Unsatisfied dependency expressed through field 'testObject'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.annotation.TestObject' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 15 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRepository': Unsatisfied dependency expressed through field 'testObject'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.annotation.TestObject' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 28 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.annotation.TestObject' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 41 more

解决方法:

 package com.itdjx.spring.annotation.repository;

 import com.itdjx.spring.annotation.TestObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; /**
* @author Wáng Chéng Dá
* @create 2017-03-03 9:24
*/
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository { @Autowired(required = false)
private TestObject testObject; @Override
public void sava() {
System.out.println("I am UserRepositoryImpl's sava method...");
System.out.println(testObject);
}
}

控制台输出:

I am UserController's execute method...
I am UserService's add method...
I am UserRepositoryImpl's sava method...
null

使用 @Resource 或 @Inject 自动装配 Bean:

Spring 还支持 @Resource 和 @Inject 注解 , 这两个注解和 @Autowired 注解的功能类似。

@Resource 注解要求提供一个 bean 名称的属性 , 若该属性为空 , 则自动采用标注出的变量或方法名作为 bean 的名称。

@Inject 和 @Autowired 注解一样也是按类型匹配注入的 bean , 但没有 required 属性。

建议使用 @Autowired 注解。

Spring学习--通过注解配置 Bean (三)的更多相关文章

  1. Spring学习--通过注解配置 Bean (二)

    在 classpath 中扫描组件: 当在组件类上使用了特定的注解之后 , 还需要在 Spring 的配置文件中声明 <context:component-scan>: base-pack ...

  2. Spring学习--通过注解配置 Bean (一)

    在 classpath 中扫描组件: 组件扫描(component scanning): Spring 能够从 classpath 下自动扫描 , 侦测和实例化具有特定注解的组件. 特定组件包括: @ ...

  3. Spring学习之xml配置Bean总结

    学习Spring时,我用的是Maven来管理jar包,先看看maven的pom.xml: pom.xml <project xmlns="http://maven.apache.org ...

  4. [原创]java WEB学习笔记103:Spring学习---Spring Bean配置:基于注解的方式(基于注解配置bean,基于注解来装配bean的属性)

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  5. Spring框架学习之注解配置与AOP思想

         上篇我们介绍了Spring中有关高级依赖关系配置的内容,也可以调用任意方法的返回值作为属性注入的值,它解决了Spring配置文件的动态性不足的缺点.而本篇,我们将介绍Spring的又一大核心 ...

  6. Spring(二)--FactoryBean、bean的后置处理器、数据库连接池、引用外部文件、使用注解配置bean等

    实验1:配置通过静态工厂方法创建的bean  [通过静态方法提供实例对象,工厂类本身不需要实例化!] 1.创建静态工厂类 public class StaticFactory { private st ...

  7. Spring(十五):通过注解配置 Bean

    在ClassPath中扫描组件 1)组件扫描(component scanning):Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件: 2)特定组件包含: --- @C ...

  8. Spring学习(七)bean装配详解之 【通过注解装配 Bean】【自动装配的歧义解决】

    自动装配 1.歧义性 我们知道用@Autowired可以对bean进行注入(按照type注入),但如果有两个相同类型的bean在IOC容器中注册了,要怎么去区分对哪一个Bean进行注入呢? 如下情况, ...

  9. IDEA02 利用Maven创建Web项目、为Web应用添加Spring框架支持、bean的创建于获取、利用注解配置Bean、自动装配Bean、MVC配置

    1 环境版本说明 Jdk : 1.8 Maven : 3.5 IDEA : 专业版 2017.2 2 环境准备 2.1 Maven安装及其配置 2.2 Tomcat安装及其配置 3 详细步骤 3.1 ...

随机推荐

  1. FIFO队列(First In First Out)和优先队列

    queue<类型名> q; q.size() - 返回队列中元素个数 q.empty() - 若队列为空,返回true ,否则返回false q.pop() - 删除队首元素,但不返回其值 ...

  2. java 获取图片大小(尺寸)

    1,获取本地图片大小(尺寸) File picture=new File(strSrc);BufferedImage sourceImg=ImageIO.read(new FileInputStrea ...

  3. javascript 之 为函数设置默认参数值

    方法一: function example(a,b){ var a = arguments[0] ? arguments[0] : 1;//设置参数a默认为1 var b = arguments[1] ...

  4. [KAFKA]kafka常用操作

    -- kafka路径示例 /opt/cloudera/parcels/KAFKA/bin-- kafka启动./kafka-server-start.sh -daemon ../config/serv ...

  5. 5.hbase表新增数据同步之add_peer

    一.前提主从集群之间能互相通讯: 二.在cluster1上(源集群):  1.查看集群已开启的peers hbase(main):011:0> list_peers PEER_ID CLUSTE ...

  6. Android Stadio调试gradle 插件 || Android Stadio 远程调试 || Anroid APT调试

    有时候,自己开发了gralde插件,想调试一下.毕竟打印log 成本太高.效率太低.怎么做呢? 第一种方法: 1.执行gradlew 命令的时候,加上几个参数:-Dorg.gradle.debug=t ...

  7. 小白学习mysql 之 innodb locks

    Innodb 锁类型: Shared and Exclusive Locks Intention Locks Record Locks Gap Locks Next-Key Locks Insert ...

  8. JAVA虚拟机(一):内存区域

    根据<java虚拟机规范第二版>规定,现阶段的java内存区域总体如下图 其中,方法区和堆是所有线程共享区域. 虚拟机栈,本地方法栈,程序计数器是各线程独占. 概述一下各个区域 先说说线程 ...

  9. 七天入门C++

  10. pta结构体链表作业

    一.PTA实验作业 7-2 1. 本题PTA提交列表 2. 设计思路 题目要求按照年龄从大到小的顺序依次输出,于是我只要用冒泡法把结构体变量从大到小排列就可以了. 3.本题调试过程碰到问题及PTA提交 ...