代码源码地址:https://github.com/wujiachengSH/springBeanDemo

概述:本章将讲解Spring对于Bean的管理方案。

目录:

  1. 准备工作
  2. 自动装配
  3. 处理装配歧义性
  4. bean的作用域
  5. 注入式声明Bean

代码环境:

  1. Sts
  2. jdk1.8
  3. spring4

1.准备工作

请在github上下载源码结合文章阅读,效果更佳

在创建了SpringBoot项目后,我们首先需要开启组件扫描,如下代码所示。

@Configuration
//扫描指定包目录
@ComponentScan(basePackages="com.wjc")
public class BeanConfig {

声明一个测试Bean的接口,全文的主要内容都是通过此接口的实现类完成的

package com.wjc.spring.bean;

public interface Bird {

    void fly();
void feed();
void twitter();
void changeTwiter();
}

2.自动装配

  自动装配是最常见的Bean装配形式。

  我们首先写一个Bird接口的实现类来展示自动装配,只需一个“@Component”注解即可完成。

package com.wjc.spring.bean.impl;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; import com.wjc.spring.bean.Bird;
//这是知更鸟
@Component
public class Robin implements Bird { private String flyStr ="知更鸟起飞";
private String feedStr = "不想吃东西";
private String twiterStr = "啊啊啊"; @Override
public void fly() {
System.out.println(flyStr);
}
@Override
public void feed() {
System.out.println(feedStr);
}
@Override
public void twitter() {
System.out.println(twiterStr);
}
@Override
public void changeTwiter() {
} }

在测试时,我们只需要使用“@Autowired”注解,就可以拿到对应的对象了

通过Junit可以测试装配是否完成

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=BeanConfig.class)
public class BeanTest { @Autowired
private Bird bird; //测试1,查看是否自动装配了知更鸟
//此时bean.impl只有robin
@Test
public void BeanTest1() {
assertNotNull(bird);
}
}

3.处理自动装配的歧义性(@Qualifier)

代码源码地址:https://github.com/wujiachengSH/springBeanDemo

试想如果我有2个Bird接口的实现类,spring在装配时是否会因为不知道具体需要哪个实现类而报错?

此时声明一个“Parrot”,也实现bird接口,运行test方法会如何?

package com.wjc.spring.bean.impl;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; import com.wjc.spring.bean.Bird;
//这是鹦鹉
@Component
public class Parrot implements Bird { private String flyStr ="鹦鹉起飞";
private String feedStr = "啥都吃";
private String twiterStr = "说人话"; @Override
public void fly() {
System.out.println(flyStr);
} @Override
public void feed() {
System.out.println(feedStr);
} @Override
public void twitter() {
System.out.println(twiterStr);
} @Override
public void changeTwiter() {
twiterStr = "你好你好";
} }

运行结果如下:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.wjc.spring.test.BeanTest': Unsatisfied dependency expressed through field 'bird'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.wjc.spring.bean.Bird' available: expected single matching bean but found 5: parrot,quail,robin,Cuckoo1,Cuckoo2
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)

 可以看到,由于Spring并不知道应该将哪一个实现类注入到bird中,报出了 “UnsatisfiedDependencyException”,我们可以通过注解“@Qualifier("parrot")”来解决此问题

//这是鹦鹉
@Component
@Qualifier("parrot")
public class Parrot implements Bird {

在获取实现类时使用如下方式,即可获取到自己想要的对象实例了

    @Autowired
@Qualifier("parrot")
private Bird parrot; //添加@Qualifier("parrot")来解决声明问题
@Test
public void BeanTest3() {
// 此时鹦鹉添加了@Primary
parrot.fly();
assertNotNull(parrot);
}

4.Bean的作用域

已知Spring默认是单例模式,但在多线程高并发的情况下,单例模式其实未必是最佳选择,如果线程A将Bean赋了值,而此时线程B拿取了被A赋值的对象,并返回了对应的结果,此时是不是会出现B返回了预料之外的结果?

本文简单讨论一下原型模式下Bean的传递,和会发生的问题,具体的各自作用域请百度“spring作用域”

已知Spring作用域如下:singleton / prototype / request  / session /global session

我们来看一下如下代码,一个原型模式的对象

package com.wjc.spring.bean.impl;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import com.wjc.spring.bean.Bird; //这是鹌鹑
//这个使用原型模式
@Component
@Qualifier("Quail")
@Scope("prototype")
public class Quail implements Bird { private String flyStr ="鹌鹑起飞";
private String feedStr = "鹌鹑想吃啥就吃啥";
private String twiterStr = "鹌鹑不知道怎么叫"; @Override
public void fly() {
// TODO Auto-generated method stub
System.out.println(flyStr);
} @Override
public void feed() {
// TODO Auto-generated method stub
System.out.println(feedStr);
} @Override
public void twitter() {
// TODO Auto-generated method stub
System.out.println(twiterStr);
} public void changeTwiter() {
twiterStr = "我大鹌鹑今天就是饿死。。。。";
} }

看下在TEST时他的表现如何:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=BeanConfig.class)
public class BeanTest3 { @Autowired
@Qualifier("Quail")
private Bird bird; @Autowired
@Qualifier("Quail")
private Bird bird2; //测试原型模式与单例的区别
@Test
public void BeanTest1() {
bird.twitter();
bird.changeTwiter();
bird.twitter(); bird2.twitter();
bird2.changeTwiter();
bird2.twitter();
}
}

运行结果:

鹌鹑不知道怎么叫
我大鹌鹑今天就是饿死。。。。
鹌鹑不知道怎么叫
我大鹌鹑今天就是饿死。。。。

spring确实将此Bean对象变成了原型模式。那么作用域是否就这么简单的完成了?

我们看一下如下代码

@Service
public class BirdServiceImpl implements BirdService { @Autowired
@Qualifier("Quail")
private Bird bird; public void ScopTest() {
bird.twitter();
bird.changeTwiter();
bird.twitter();
}
}

运行测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=BeanConfig.class)
public class ServiceTest { @Autowired
private BirdService birdService; @Autowired
private BirdService birdService2; //测试在Service上添加和不添加@Qualifier("Quail")时调用的Bean的区别
@Test
public void ServiceTest2() {
birdService.ScopTest();
birdService2.ScopTest();
}
}

运行结果:

鹌鹑不知道怎么叫
我大鹌鹑今天就是饿死。。。。
我大鹌鹑今天就是饿死。。。。
我大鹌鹑今天就是饿死。。。。

????????原型模式失效了????

为什么会发生这种情况?因为在此场景下,“BirdServiceImpl”是单例模式的,对Bean的操作不可避免的变成了单例的,如果添加如下代码结果就会完全不一样

@Service
@Scope("prototype")
public class BirdServiceImpl implements BirdService { @Autowired
@Qualifier("Quail")
private Bird bird; public void ScopTest() {
bird.twitter();
bird.changeTwiter();
bird.twitter();
}
}

再次运行时:

鹌鹑不知道怎么叫
我大鹌鹑今天就是饿死。。。。
鹌鹑不知道怎么叫
我大鹌鹑今天就是饿死。。。。

假设“ServiceTest”方法为Control层,“BirdServiceImpl”方法为Service层,“Quail”为Bean,在实际应用时,应该考虑Scop注解是否会可以成功生效。

如下为测试后的结果

    //当Service上有@Scope("prototype"),Bean上有@Scope("prototype")时 返回不同对象
//当Service上有@Scope("prototype"),Bean上无@Scope("prototype")时 返回相同对象
//当Service上无@Scope("prototype"),Bean上有@Scope("prototype")时 返回相同对象
//当Service上无@Scope("prototype"),Bean上无@Scope("prototype")时 返回相同对象

5.注入式声明Bean

在上述代码中,我都是通过硬编码的形式在输入一些内容的,那么能否通过读取配置文件的方式完成输出内容呢?(实际运用场景:获取数据库连接对象Session)

我们首先定义一个对象,可以看到我没有添加任何注解,因为此对象不需要在这里进行装配!

package com.wjc.spring.bean.impl;

import com.wjc.spring.bean.Bird;
//这是杜鹃
public class Cuckoo implements Bird { private String flyStr = "fly" ;
private String feedStr = "feed";
private String twiterStr = "twiter"; public Cuckoo(String flyStr, String feedStr, String twiterStr) {
super();
this.flyStr = flyStr;
this.feedStr = feedStr;
this.twiterStr = twiterStr;
} @Override
public void fly() {
// TODO Auto-generated method stub
System.out.println(flyStr);
} @Override
public void feed() {
// TODO Auto-generated method stub
System.out.println(feedStr);
} @Override
public void twitter() {
// TODO Auto-generated method stub
System.out.println(twiterStr);
} @Override
public void changeTwiter() {
// TODO Auto-generated method stub
twiterStr = "杜鹃";
} }

我们将Config改造一下,由他来负责装配对象

package com.wjc.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import com.wjc.spring.bean.impl.Cuckoo; @Configuration
//扫描指定包目录
@ComponentScan(basePackages="com.wjc")
@PropertySource("classpath:Cuckoo.properties")
public class BeanConfig {
//开启组件扫描
//获取资源
@Autowired
private Environment env; //通过配置文件装配Cuckoo
@Bean(name="Cuckoo1")
public Cuckoo getbird() { return new Cuckoo(env.getProperty("flyStr","fly"),
env.getProperty("feedStr","feed"), env.getProperty("twiterStr","twiter")); //return new Cuckoo("fly","feed", "twiter"); }
@Bean(name="Cuckoo2")
public Cuckoo getbird2() { return new Cuckoo("fly","feed", "twiter"); } }

可以看到我声明了2个"Cuckoo"对象实例,分别叫“Cuckoo1”,“Cuckoo2”

使用Test方法来执行一下

package com.wjc.spring.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.wjc.spring.bean.impl.Cuckoo;
import com.wjc.spring.config.BeanConfig; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=BeanConfig.class)
public class BeanTest4 { @Autowired
@Qualifier("Cuckoo2")
private Cuckoo Cuckoo; @Autowired
@Qualifier("Cuckoo1")
private Cuckoo Cuckoo1;
//测试通过配置文件装配Bean
@Test
public void BeanTest1() {
Cuckoo1.fly();
Cuckoo1.feed();
Cuckoo1.twitter();
Cuckoo.fly();
Cuckoo.feed();
Cuckoo.twitter();
} }

执行结果

cuckoo fly
cuckoo feed
cuckoo twiter
fly
feed
twiter

可以看到成功的声明了对象。

本文章为在下在查看SPRING实战一书和工作上发生过的问题结合来完成的。希望各位看官指点错误和不合理的地方。

代码源码地址:https://github.com/wujiachengSH/springBeanDemo

Spring实战拆书--SpringBean的更多相关文章

  1. Spring Bean的生命周期,《Spring 实战》书中的官方说法

    连着两天的面试 ,都问到了 Spring 的Bean的生命周期,其中还包括 昨晚一波阿里的电话面试.这里找到了Spring 实战中的官方说法.希望各位要面试的小伙伴记住,以后有可能,或者是有时间 去看 ...

  2. Spring实战6:利用Spring和JDBC访问数据库

    主要内容 定义Spring的数据访问支持 配置数据库资源 使用Spring提供的JDBC模板 写在前面:经过上一篇文章的学习,我们掌握了如何写web应用的控制器层,不过由于只定义了SpitterRep ...

  3. Spring实战——无需一行xml配置实现自动化注入

    已经想不起来上一次买技术相关的书是什么时候了,一直以来都习惯性的下载一份电子档看看.显然,如果不是基于强烈的需求或强大的动力鞭策下,大部分的书籍也都只是蜻蜓点水,浮光掠影. 就像有位同事说的一样,有些 ...

  4. 《Spring实战》学习笔记-第五章:构建Spring web应用

    之前一直在看<Spring实战>第三版,看到第五章时发现很多东西已经过时被废弃了,于是现在开始读<Spring实战>第四版了,章节安排与之前不同了,里面应用的应该是最新的技术. ...

  5. 【Spring实战】—— 1 入门讲解

    这个系列是学习spring实战的总结,一方面总结书中所写的精髓,另一方面总结一下自己的感想. 基础部分讲解了spring最为熟知的几个功能:依赖注入/控制反转 和 面向切面编程. 这两个就不再多说了, ...

  6. Spring实战(中文4,5版) PDF含源码

    Spring实战 读者评价 看了一半后在做评论,物流速度挺快,正版行货,只是运输过程有点印记,但是想必大家和你关注内容,spring 4必之3更加关注的是使用注解做开发,对于初学者还是很有用,但是不排 ...

  7. spring实战学习笔记(一)spring装配bean

    最近在学习spring boot 发现对某些注解不是很深入的了解.看技术书给出的实例 会很疑惑为什么要用这个注解? 这个注解的作用?有其他相同作用的注解吗?这个注解的运行机制是什么?等等 spring ...

  8. 将Spring实战第5版中Spring HATEOAS部分代码迁移到Spring HATEOAS 1.0

    最近在阅读Spring实战第五版中文版,书中第6章关于Spring HATEOAS部分代码使用的是Spring HATEOAS 0.25的版本,而最新的Spring HATEOAS 1.0对旧版的AP ...

  9. Spring实战第4版PDF下载含源码

    下载链接 扫描右侧公告中二维码,回复[spring实战]即可获取所有链接. 读者评价 看了一半后在做评论,物流速度挺快,正版行货,只是运输过程有点印记,但是想必大家和你关注内容,spring 4必之3 ...

随机推荐

  1. 用turtle库实现汉诺塔问题~~~~~

    汉诺塔问题 问题描述和背景: 汉诺塔是学习"递归"的经典入门案例,该案例来源于真实故事.‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬ ...

  2. Java 初学UDP传输

    不谈理论,先举简单例子. 发送端代码: public class UDPDemo { public static void main(String[] args) throws Exception { ...

  3. 关于mysql存储过程中传decimal值会自动四舍五入的这个坑

    容我说几句题外话:我的工作日常是用微软系的,SQL SERVICE 存储过程很强大,我也很习惯很喜欢用存储过程.和MySQL结缘,是在五年前,因为一些原因,公司要求用开源免费的数据库.很多时候,用my ...

  4. Spring-MVC运行原理

    一. Spring-MVC的对象初始化,即 bean放入context的beanFactory中. 1. 对象的初始化工作主要在org.springframework.web.servlet.Fram ...

  5. java线程中的notifyAll唤醒操作

    注意: java中的notifyAll和notify都是唤醒线程的操作,notify只会唤醒等待池中的某一个线程,但是不确定是哪一个线程,notifyAll是针对指定对象里面的所有线程执行唤醒操作,指 ...

  6. angular的json

    在angular从servlet中获取的list数据是字符串格式,需要转为json格式,于是使用语法: $scope.findOne=function(id){ typeTemplateService ...

  7. 猜数字游戏;库的使用:turtle

    myNum = print('猜字游戏\n') while True: guess = int(input('请输入一个数:')) if guess > myNum: print('不对哦猜大了 ...

  8. Effective Java -- 使可变性最小化

    为了使类成为不可变的,应该遵循以下五条原则: 1. 不要提供任何会下盖对象状态的方法 2. 保证类不会被扩展 3. 使所有的域都是final的 4. 使所有的域都成为私有的 5. 确保对于任何可变组件 ...

  9. dedecms mvc 开发

    目录结构说明: |_app    |___control      控制器(C)    |___model        模型(M)    |___templates    视图模板(V)    |_ ...

  10. 文件在线预览doc,docx转换pdf(一)

    文件在线预览doc,docx转换pdf(一) 1. 前言 文档转换是一个是一块硬骨头,但是也是必不可少的,我们正好做的知识库产品中,也面临着同样的问题,文档转换,精准的全文搜索,知识的转换率,是知识库 ...