一、Spring配置的可选方案

  三种主要的装配机制:

     在xml文件中进行显示配置;

     在java中进行显示配置;

     隐式的bean发现机制和自动装配。

  使用建议:尽可能使用自动配置的机制,显示配置越少越好,若必须要显式配置bean的时候,(例如有些源码并非自己维护,需要为这些代码配置bean的时候),推荐使用类型安全并且比XML更加强大的JavaConfig,

       只有当你想要使用遍历的XMl命名空间,并且在JavaConfig中同样没有实现是,才使用XML。

二、自动化装配bean

  2.1 Spring从两个角度来实现自动化装配

    组件扫描(component scanning):Spring会自动发现应用的上下文中所创建的bean。

    自动装配(autowiring):Spring自动满足bean之间的依赖。

  CompactDisc接口在Java中定义CD的概念

 package soundsystem;

 public interface CompactDisc{
void play();
}

  

  带有@Component注解的CompactDisc实现类SgtPeppers

 package soundsystem;

 import org.springframework.stereotype.Component;

 @Component
public class SgtPeppers implements CompactDisc {
private String title = "Sgt.Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles"; public void play() {
System.out.println("Playing " + title + " by " + artist);
}
}

  此处实现类功能暂时不重要,重要的是 @Component注解的作用:表明该类会作为组件类,并告知Spring需要为这个类创建bean,故而不需要显式配置SgtPeppers bean。

  

  @ComponentScan注解启用了组件扫描

 package soundsystem;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan
public class CDPlayerConfig {
}

  组件扫描默认是不启用的,需要显式的配置Spring,此处通过Java代码定义了Spring的装配规则,在Spring中启用组件扫描。

  在没有其他配置下,@ComponentScan只会默认扫描与配置类相同的包。

当然,也可以用XML文件来启用组件扫描,即可以使用Spring context命名空间的<context:component-scan>元素。

  通过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">
<context:component-scan base-package="soundsystem"/>
</beans>

  2.2 为组件扫描的bean命名

    Spring应用上下文会把所有的bean都会给一个ID,尽管上文SgtPeppers bean并未明确的设置ID,但Spring会默认的设置该bean ID为sgtPeppers,但若你想把期望的ID作为值传递给@Component注解,比如将这个bean标识为lonelyHeartClub,则配置如下:

@Component("lonelyHeartsClub")
public class SgtPeppers implements CompactDisc {
...
}

    设置组件扫描的基础包:

   如果需要指定包,需要在@ComponentScan的value属性指定包名称:@ComponentScan("soundsystem");

   若想表明所设置的是基础包,可以通过basePackages属性:@ComponentScan(basePackages="soundsystem");

   basePackages可以设置多个基础包,如@ComponentScan(basePackages="soundsystem","video")

  2.3 通过为bean添加注解实现自动装配 

@Autowired
public CDPlayer(CompactDisc cd){
this.cd = cd
}

   即通过@Autowired注解在构造器之上,当然@Autowired注解不仅能够用在构造器之上,还能用在属性的Setter方法。

三、通过java代码装配bean

  3.1 创建配置类

  修改CDPlayerConfig的配置:

package soundsystem;

import org.springframework.context.annotation.Configuration;

@Configuration
public class CDPlayerConfig { }

  3.2 声明简单的bean

  在JavaConfig中申明bean,需要编写一个方法,这个方法会创建所需类型的实例,然后给这个方法添加@Bean注解,如下方代码:

@Bean
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}

  @Bean 注解会告诉Spring这个方法将会返回一个对象,该对象要注册为Spring应用上下文中的bean。

  默认情况下,bean的ID与带有@Bean注解的方法名是一样的。

  也可以通过name属性指定一个不同的名字:

@Bean(name="lonelyHeartsClubBand")
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}

四、通过XML装配bean

  4.1 创建XML配置规范

  在XML配置中,意味着要创建一个XML文件,并且要以<beans>元素为根。

  最简单的Spring 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--configuration details go here-->
</beans>

  4.2 声明一个简单的<bean>

  声明CompactDisc bean:

<bean class="soundsystem.SgtPeppers"/>

  4.3 借助构造器注入初始化bean

<bean id ="cdPlayer" class ="soundsystem.CDPlayer">
<constructor-arg ref = "compactDisc"/>
</bean>

  当Spring遇到这个<bean> 元素,它会创建一个CDPlayer实例。<constructor-arg>元素会告知Spring 要将一个ID为compactDisc的bean引用传递到CDPlayer的构造器中。

  

五、导入和混合配置

  5.1 在JavaConfig中引用XML配置

  1、如果需要将两个类组合在一起,使用方式就是使用@Import注解导入另一个类,如在CDPlayerConfig类中导入CDConfig:

package soundsystem;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; @Configuration
@Import(CDConfig.class)
public class CDPlayerConfig {
@Bean
public CDPlayer cdPlayer(CompactDisc compactDisc) {
return new CDPlayer(compactDisc));
}
}

  2、或者采用一个更好的办法,也就是不在CDPlayerConfig中使用@Import,而采用一个更高级别的SoundSystemConfig,在这个类中使用@Import将两个配置类组合在一起:

package soundsystem;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; @Configuration
@Import({CDConfig.class,CDPlayerConfig.class})
public class SoundSystemConfig{ }

  3、让Spring同时加载XML配置文件以及其他基于Java的配置:

package soundsystem;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource; @Configuration
@Import(CDPlayerConfig.class)
@ImportResource("classpath:cd-config.xml")
public class SoundSystemConfig{ }

  5.2 在XML配置中引用JavaConfig

   将BlankDisc bean 拆分到自己的配置文件中,该文件名为cd-config.xml,在XML配置文件中使用<import> 元素来引用该文件:

 <?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="cd-config.xml"/>
<bean id="cdPlayer"
class="soundsystem.CDPlayer"
c:cd-ref = "compactDisc"/>
</beans>

   为了将JavaConfig类导入到XML配置中,可以这样声明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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="soundsystem.CDConfig"/>
<bean id="cdPlayer"
class="soundsystem.CDPlayer"
c:cd-ref = "compactDisc"/>
</beans>

参考文档:《Spring实战第4版》

注:本篇学习文章的实例代码以及内容大多数来源于参考文档,仅供本人参考学习,加深理解之用,无任何商业用途,转载请与本人联系,若私自转载用于商业用途,一切后果自负。

  

Spring基础(一)------装配Bean的更多相关文章

  1. Spring 之自动化装配 bean 尝试

    [Spring之自动化装配bean尝试] 1.添加dependencies如下所示(不是每一个都用得到 <dependencies> <dependency> <grou ...

  2. Spring总结 1.装配bean

    本随笔内容要点如下: 依赖注入 Spring装配bean的方式 条件化装配 一.依赖注入 我理解的依赖注入是这样的:所谓的依赖,就是对象所依赖的其他对象.Spring提供了一个bean容器,它负责创建 ...

  3. spring中自动装配bean

    首先用@Component注解类: package soundsystem: import org.springframework.stereotype.Component; @Component p ...

  4. spring的自动装配Bean与自动检测Bean

    spring可以通过编写XML来配置Bean,也可以通过使用spring的注解来装配Bean. 1.自动装配与自动检测: 自动装配:让spring自动识别如何装配bean的依赖关系,减少对<pr ...

  5. Spring框架---IOC装配Bean

    IOC装配Bean (1)Spring框架Bean实例化的方式提供了三种方式实例化Bean 构造方法实例化(默认无参数,用的最多) 静态工厂实例化 实例工厂实例化 下面先写这三种方法的applicat ...

  6. spring学习总结——装配Bean学习一(自动装配)

    一.Spring配置的可选方案 Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系.但是,作为开发人员,你需要告诉Spring要创建哪些bean并且如何将其装配在一起.当描 ...

  7. Spring实战之装配Bean

    1.1Spring配置的可选方案 Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系.但是,作为开发人员,你需要告诉Spring要创建哪些bean并且如何将其装配在一起.当 ...

  8. Spring学习(二)--装配Bean

    一.Spring装配机制 Spring提供了三种主要的装配机制: 1.在XML中进行显示配置 2.在Java中进行显示配置 3.隐式的bean发现机制和自动装配--自动化装配bean Spring可以 ...

  9. Spring学习笔记—装配Bean

    在Spring中,对象无需自己负责查找或创建与其关联的其他对象.相反,容器负责把需要相互协作的对象引用赋予各个对象.创建应用对象之间协作关系的行为通常称为装配(wiring),这也是依赖注入的本质. ...

随机推荐

  1. java知识随笔整理-数据库的临时表

    1.创建临时表的方法 方法一.select * into #临时表名 from 你的表; 方法二. create table #临时表名(字段1 约束条件,字段2 约束条件,.....)create ...

  2. 分享 Shiro 学习过程中遇到的一些问题

    最近在学习 shiro 安全框架后,自己手写了一个小的管理系统 web 项目,并使用 shiro 作为安全管理框架.接下来分享一下在这过程中,遇到的一些问题以及自己的解决思路和方法. 一.Log ou ...

  3. centos8自定义目录安装php7.3

    1.目录结构 源码目录:/home/werben/pkgsrc/php-7.3.11 安装目录:/home/werben/application/php7.3.11 2.下载php源码 # 官网地址: ...

  4. 第十三章 ZYNQ-MIZ701 TIMER定时器中断

      上篇文章实现了了PS接受来自PL的中断,本片文章将在ZYNQ的纯PS里实现私有定时器中断.每隔一秒中断一次,在中断函数里计数加1,通过串口打印输出. 本文所使用的开发板是Miz701 PC 开发环 ...

  5. 牛客 203B tree(树形dp)

    大意: 给定树, 对于每个节点, 求包含该节点的连通子集数. 显然有$dp[x]=\prod (dp[y]+1), ans[x]=(\frac{ans[fa[x]]}{dp[x]+1}+1)dp[x] ...

  6. 怎样使用yum安装nginx

    yum install -y nginx 以上.

  7. linux脚本监控应用且通过邮件报警异常

    一.背景 最近接到监控应用并通过邮件报警的任务,由于需求比较简单,故没有使用springboot那套,而是采用linux脚本的方式进行监控. 二.思路 通过linux自带的定时功能,定时执行一个lin ...

  8. MongoDB查询操作 返回指定字段(C#官方驱动)

    首先,MongoDB中返回指定的字段的查询方法如下: db.person.find({Name:"小丑"},{Age:1,Sex:1}) 该语句表示:查询person表中name为 ...

  9. json字符转java bean忽略大小写

    使用objectMapper进行json字符的解析 com.fasterxml.jackson.databind.ObjectMapper ob =new com.fasterxml.jackson. ...

  10. ThreadPoolExecutor的runState和workCount变量怎么存储?

    在阅读Java线程池ThreadPoolExecutor源码的时候,发现它很巧妙地把线程池状态runState和线程数workCount两个变量存放在了一个int型变量里面. 我们先看一个数值,如下是 ...