本随笔内容要点如下:

  • 依赖注入
  • Spring装配bean的方式
  • 条件化装配

一、依赖注入

  我理解的依赖注入是这样的:所谓的依赖,就是对象所依赖的其他对象。Spring提供了一个bean容器,它负责创建应用程序中的bean并通过依赖注入来协调这些对象之间的关系,实现自动创建与管理所创建的对象。我们只需要通过配置来命令Spring提供的容器来完成bean的装配。

二、Spring装配bean的方式

  在Spring中,装配bean有三种方式:

  1. 通过xml进行配置
  2. 通过Java进行配置
  3. 通过注解来自动扫描并配置

  先使用xml进行举例:

 package cn.powerfully.domain;

 public class ABean {
private String str;
private double num; public ABean() {
} public ABean(String str, double num) {
this.str = str;
this.num = num;
} public String getStr() {
return str;
} public void setStr(String str) {
this.str = str;
} public double getNum() {
return num;
} public void setNum(double num) {
this.num = num;
}
}

在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"> <bean id="aBean" class="cn.powerfully.domain.ABean">
<constructor-arg name="str" value="bean"/>
<constructor-arg name="num" value="3.1415926"/>
</bean> </beans>

   使用bean标签来表示装载一个bean到Spring容器,默认该bean为单例,即容器中只有一个该类对象。对于字段的注入,上面使用了构造器注入,Spring还支持setter注入,通过<property>标签进行注入,具体的可以参考帮助文档。为了简化,spring提供了c命名空间和p命名空间,用来简化构造器注入和setter注入,上面的例子可以改编成如下:

<?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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- <bean id="aBean" class="cn.powerfully.domain.ABean" p:str="p namespace" p:num="3.14" /> -->
<bean id="aBean" class="cn.powerfully.domain.ABean" c:str="c namespace" c:num="3.14" /> </beans>

  其他基本类型和上面的例子一样,直接编写即可。对于注入对象与集合,将有所不同:

 package cn.powerfully.domain;

 import java.util.List;
import java.util.Map;
import java.util.Properties; public class BBean { private ABean aBean;
private List<String> list;
private Map<String, Integer> map;
private Properties props; public ABean getaBean() {
return aBean;
} public void setaBean(ABean aBean) {
this.aBean = aBean;
} public List<String> getList() {
return list;
} public void setList(List<String> list) {
this.list = list;
} public Map<String, Integer> getMap() {
return map;
} public void setMap(Map<String, Integer> map) {
this.map = map;
} public Properties getProps() {
return props;
} public void setProps(Properties props) {
this.props = props;
} }

  实例化该类时,需要注入对象、List、Map、Properties,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:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- <bean id="aBean" class="cn.powerfully.domain.ABean" p:str="p namespace" p:num="3.14" /> -->
<bean id="aBean" class="cn.powerfully.domain.ABean" c:str="c namespace" c:num="3.14" /> <bean id="bBean" class="cn.powerfully.domain.BBean" p:aBean-ref="aBean">
<!-- <property name="aBean" ref="aBean" /> -->
<property name="list">
<list>
<value>item1</value>
<value>item2</value>
</list>
</property>
<property name="map">
<map>
<entry key="key1" value="1" />
<entry key="key2" value="2" />
</map>
</property>
<property name="props">
<props>
<prop key="key1">1</prop>
<prop key="key2">2</prop>
</props>
</property>
</bean> </beans>

  如果想注入对象,则需要使用ref属性而不是value属性,ref属性值为bean对象的id。特别注意的是,如果使用p或c命名空间,其格式为c:propertyName-ref。常见的集合注入如上配置。关于具体的配置参见帮助文档,毕竟本随笔只是我的知识点简要回忆。

  接着是Java配置,个人觉得Java配置会比xml配置来得更爽,它具有很强的灵活性。还是使用上面的例子,配置如下:

 package cn.powerfully.config;

 import java.util.Arrays;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import cn.powerfully.domain.ABean;
import cn.powerfully.domain.BBean; @Configuration
public class BeanConfig { @Bean
public ABean aBean() {
return new ABean("java configura", 3.1415);
} @Bean
public BBean bBean(ABean aBean) {
BBean bean = new BBean();
bean.setaBean(aBean);
bean.setList(Arrays.asList("item1", "item2"));
return bean;
} }

  通过注解@Configuration来表明该类是配置类,通过@Bean来表示该方法返回结果将放入容器,而方法返回结果即实例对象需要自己创建,其中在容器中bean的id为方法名。对于bBean,需要注入aBean对象,只需要在方法中填入参数,接着在代码里面直接引用即可。

  最后,回忆下注解。一般用到的注解为@Component与@Autowired。@Component标记在类上,表示该类需要被实例化并由Spring容器管理。@Autowired表示需要在Spring容器中查找符合的bean来设置到当前属性里,该注解可以用在字段、构造器、setter上。同时,还要开启自动扫描才能实现。

三、条件化装配

  有时,我们需要动态地来装配bean。当满足一定条件时我们才需要装配这个bean。Spring4之后,注解@Conditional可以实现这个功能。

 @Conditional(UserCondition.class)
public class User {} public class UserCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return false;
}
}

  当UserCondition中matches方法返回真时,才会创建User对象。关于该接口的具体使用请参考另一篇博文(还没写~.~)。

  其中@Profile是其中的一个特例,它也是使用@Conditonal来实现的。配置完该注解后,我们一开始可以通过设置profile类型来管理需要创建哪一系列bean。例如,在Web开发中,我们所选择的数据库可能根据运行时期的不同而不同。例如在开发环境,我们可能使用c3p0、dbcp等作为数据源。而在生产环境中,我们可能使用JNDI数据源。这是我们就可以使用profile了。我们先为不同的配置设置不同的profile,然后再使用时设置profile就行了。具体的还是参考另一篇博文。>_<

  简单例子如下:

  定义交通工具接口

 package cn.powerfully.domain;

 public interface Vehicle {}

  定义车与飞机类并实现Vehicle接口:

 package cn.powerfully.domain;

 import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; @Component
@Profile("car")
public class Car implements Vehicle {
@Override
public String toString() {
return "Car";
}
}
 package cn.powerfully.domain;

 import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; @Component
@Profile("plane")
public class Plane implements Vehicle {
@Override
public String toString() {
return "Plane";
}
}

  创建配置类

 package cn.powerfully.config;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan(basePackages = "cn.powerfully.domain")
public class VehicleConfig {}

  JUnit测试

 package cn.powerfully.test;

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.powerfully.config.VehicleConfig;
import cn.powerfully.domain.Vehicle; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=VehicleConfig.class)
@ActiveProfiles("car")
public class Demo {
@Autowired
private Vehicle vehicle; @Test
public void test(){
System.out.println(vehicle);
}
}

  当选用了car时,输出Car,选择plane时,输出了Plane...当然也可以使用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:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <beans profile="car">
<bean id="vehicle" class="cn.powerfully.domain.Car" />
</beans> <beans profile="plane">
<bean id="vehicle" class="cn.powerfully.domain.Plane" />
</beans> </beans>

  注意profile属性是位与beans标签上的。

Spring总结 1.装配bean的更多相关文章

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

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

  2. spring中自动装配bean

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

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

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

  4. Spring学习笔记—装配Bean

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

  5. spring实战三装配bean之Bean的作用域以及初始化和销毁Bean

    1.Bean的作用域 所有的spring bean默认都是单例.当容器分配一个Bean时,不论是通过装配还是调用容器的getBean()方法,它总是返回Bean的同一个实例.有时候需要每次请求时都获得 ...

  6. spring实战一:装配bean之注入Bean属性

    内容参考自spring in action一书. 创建应用对象之间协作关系的行为通常称为装配,这也是依赖注入的本质. 1. 创建spring配置 spring是一个基于容器的框架.如果没有配置spri ...

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

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

  8. 【Spring 核心】装配bean(二) JavaConfig装配

    前面介绍完了组件扫描和自动装配,这里再来看一下装配bean的另一种方式JavaConfig. 包路径: src/main/java com.bonc-|--config--|--CDPlayerCon ...

  9. Spring系列之装配Bean

    Spring 的三种装配Bean的方式 组件扫描+自动装配(隐式) 通过Java config装配bean(显示) 通过XML装配bean(显示) 一.组件扫描+自动装配(隐式配置) 组件扫描: Sp ...

随机推荐

  1. html5+javascript的管廊监控页面

    这周二做的,支持苹果手机,安卓手机,电脑,平板访问

  2. hdu 4975 最大流快版

    http://acm.hdu.edu.cn/showproblem.php?pid=4975 给出每行每列的和,问是否存在这样的表格:每个小格放的数字只能是0--9. 直接用第八场最大流模板. #in ...

  3. codeforces 434D

    题意:有n<=50个点,每个点有xi有[li, ri]种取值,-100 <= li <= ri <= 100,并且给定m<=100条边,每条边为u,v,d表示xu< ...

  4. Javascript 对象创建多种方式 原型链

    一.对象创建 1.new Object 方式 直接赋上属性和方法 var obj = new Object(); obj.name = '娃娃'; obj.showName = function(){ ...

  5. 2.虚拟机安装的ubuntu全屏显示

    虚拟机下面安装了ubuntu系统,显示的屏幕只有那么一小块儿,不知道如何才能全屏,那么如何全屏呢?且看下面经验. 方法/步骤 打开虚拟机,并点击要更改成全屏的那个ubuntu系统的电源 我的虚拟机名字 ...

  6. 7.css浮动与定位

    外边距塌陷 解决方案: ◆给父盒子加border ◆overflow:hidden; bfc 行内元素可以定义左右的内外边距,上下会被忽略掉. 行内块可以定义内外边距. 文档流(标准流) 元素自上而下 ...

  7. delphi 过滤开头 结尾 全部 空格的函数

    function TrimAnsi(const S: AnsiString): Ansistring; var I, L: Integer; begin L := Length(S); I := ; ...

  8. 关于scanf、getchar、getch、getche缓冲区分析——C语言

    缓冲区 根据数据刷新的时机可以将缓冲区的类型分为:全缓冲.行缓冲.无缓冲 (注意:Windows下的输出设备没有缓冲区,意思是printf是无缓冲的,但是在Linux下printf就是行缓冲的,至于为 ...

  9. mac终端常用命令

    1.du #查看文件目录大小 示例:查看DataCenter目录下所有文件/文件夹的大小 everSeeker:DataCenter pingping$ -h .9G ./Books 1.2M ./C ...

  10. 程序猿的日常——Mybatis现学现卖

    最近有一个小项目需求,需要用spring mvc + mybatis实现一个复杂的配置系统.其中遇到了很多不太常见的问题,在这里特意记录下: 主要涉及的内容有 事务 多表删除 插入并返回主键 1 sp ...