本随笔内容要点如下:

  • 依赖注入
  • 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. Java理论学时第六节。课后作业。

    package Fuction; class Grandparent { public Grandparent() { System.out.println("GrandParent Cre ...

  2. C#将XML转换成JSON 使用 JavaScript 将 XML 转成 JSON

    如何在ASP.NET中用C#将XML转换成JSON [JavaScript]代码 // Changes XML to JSON function xmlToJson(xml) { // Create ...

  3. redis简单使用

    主要参考资料:http://wiki.jikexueyuan.com/project/redis-guide/data-type.html一.redis 安装1.在官网下载安装包2.解压安装包 tar ...

  4. 一.认识python.变量.数据类型.条件if

    01.万恶之源-python基础 ⼀.python介绍  python的创始⼈为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决⼼ ...

  5. nodeclub config

    配置文件,本来想着分成好几个文件,放在一个文件夹中,后来觉得也没必要,原因是,配置文件看一遍也就记住了,分开反而显得繁琐,注释写清楚就好. // 路径模块 var path = require('pa ...

  6. title

    事实上 @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import ur ...

  7. mssql借助链接服务器进行数据快速迁移

    在工作中,遇到了一个任务,需要将A数据库的数据迁移到B数据库,两个数据库的数据结构是一样的.B数据库已经在相当数量的数据了,故而不能通过复制数据库的方式来实现.  旧方法 在对数据迁移的时候,一开始使 ...

  8. ASP .Net C# ---CSV导入导出

    CSV和Excel大致相同  复制下来 数据传到方法里面就可以了 /// <summary> /// DataTable数据写入CSV文件 /// </summary> /// ...

  9. Java代码审计连载之—添油加醋

    在代码审计中,按业务流程审计当然是必须的,人工的流程审计的优点是能够更加全面的发现漏洞,但是缺点是查找漏洞效率低下.如果要定向的查找漏洞,逆向跟踪变量技术就显得更加突出,如查找XSS.SQL注入.命令 ...

  10. java String 内存模型

    关于java的内存模型,参照以下的一篇文章: https://isudox.com/2016/06/22/memory-model-of-string-in-java-language/