本随笔内容要点如下:

  • 依赖注入
  • 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. (01背包 先排序)Proud Merchants (hdu 3466)

    http://acm.hdu.edu.cn/showproblem.php?pid=3466   Description Recently, iSea went to an ancient count ...

  2. Codeforces812B Sagheer, the Hausmeister 2017-06-02 20:47 85人阅读 评论(0) 收藏

    B. Sagheer, the Hausmeister time limit per test 1 second memory limit per test 256 megabytes input s ...

  3. ORACLE EBS常用表

    http://www.cnblogs.com/quanweiru/archive/2012/09/26/2704628.html call fnd_global.APPS_INITIALIZE(131 ...

  4. [杂谈] 一个关于 as 的小测试

    代码如下:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 procedure TForm1.Button1Click(Sender: TObject); va ...

  5. SQL Server 字符串拼接、读取

    一.查询结果使用,字符串拼接 declare @names nvarchar(1000) declare @ParmDefinition nvarchar(1000) declare @sqltext ...

  6. JS学习笔记7_表单脚本

    1.获取表单及表单元素引用的方式 var mForm = document.forms[formName];获取表单引用 mForm.elements[elemName]获取表单元素,如有同名的,则得 ...

  7. CentOS7下让Asp.Net Core的网站自动运行

    一.安装Nginx yum install nginx 二.配置Nginx vi /etc/nginx/nginx.conf location / { proxy_pass http://127.0. ...

  8. 【转】Windows Server 2016 安装 IIS 服务时提示指定备用源路径

    原文地址:http://www.codingwhy.com/view/973.html 在Windows Serever 2016中安装IIS的时候,遇到以下提示 是否需要指定备用源路径?一个或多个安 ...

  9. 【spring cloud】spring cloud2.X spring boot2.0.4调用feign配置Hystrix Dashboard 和 集成Turbine 【解决:Hystrix仪表盘Unable to connect to Command Metric Stream】【解决:Hystrix仪表盘Loading...】

    环境: <java.version>1.8</java.version><spring-boot.version>2.0.4.RELEASE</spring- ...

  10. harbor镜像仓库-01-搭建部署

    harbor镜像仓库-01-搭建部署 dockerregistryharbor安装部署docker-compose harbor的https配置参考另一章节harbor镜像仓库-02-https访问配 ...