本文讲解了构造注入以及spring的基本使用方式,通过一个杂技演员的例子,讲述了依赖注入属性或者对象的使用方法。

  如果想要使用spring来实现依赖注入,需要几个重要的步骤:

  1 定义主要的类和需要分离的属性。这里主要的类,是指程序的主要对象,在例子中是Juggler杂技员。而想要分离构造的属性,是它手中的袋子的数目beanBags。

  2 配置bean.xml。通过配置文件,确定主要的类和属性之间的关系,以及实现类。

  3 通过应用上下文,获取bean,并进行使用。

注入属性

  实例代码:

  1 表演者接口:Performer.java

package com.spring.test.action1;

public interface Performer {
void perform() throws PerformanceException;
}

  2 杂技员:Juggler,继承了表演者接口

package com.spring.test.action1;

public class Juggler implements Performer{
private int beanBags = ; public Juggler(){ } public Juggler(int beanBags){
this.beanBags = beanBags;
} public void perform() throws PerformanceException {
System.out.println("Juggler "+beanBags+" beanBags");
} }

  3 Spring配置文件:bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="duke" class="com.spring.test.action1.Juggler">
<constructor-arg value=""/>
</bean>
</beans>

  4 应用上下文获取指定的bean

package com.spring.test.action1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
Performer performer = (Performer)ctx.getBean("duke");
try {
performer.perform();
} catch (PerformanceException e) {
e.printStackTrace();
}
}
}

  执行结果如下:

Juggler  beanBags

注入对象

  1 例如,上面的杂技演员不仅仅会仍袋子,还会表演诗歌,那么诗歌这个对象就需要注入到表演者的构造函数中,可以如下表示会朗诵诗歌的杂技演员:PoeticJuggler

package com.spring.test.action1;

public class PoeticJuggler extends Juggler{
private Poem poem; public PoeticJuggler(Poem poem){
super();
this.poem = poem;
} public PoeticJuggler(int beanBags,Poem poem){
super(beanBags);
this.poem = poem;
} public void perform() throws PerformanceException {
super.perform();
System.out.println("While reciting...");
poem.recite();
} }

  2 诗歌对象:Sonnet29

package com.spring.test.action1;

public class Sonnet29 implements Poem{
private static String lines = "嘛咪嘛咪哄"; public Sonnet29() { } public void recite() {
System.out.println(lines);
} }

  3 Bean.xml配置文件如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="duke" class="com.spring.test.action1.Juggler">
<constructor-arg value=""/>
</bean>
<bean id="sonnet29" class="com.spring.test.action1.Sonnet29"/>
<bean id="poeticDuke" class="com.spring.test.action1.PoeticJuggler">
<constructor-arg value=""/>
<constructor-arg ref="sonnet29"/>
</bean>
</beans>

  4 主要的执行代码,通过应用上下文获取制定的bean

package com.spring.test.action1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
// Performer performer = (Performer)ctx.getBean("duke");
Performer performer1 = (Performer)ctx.getBean("poeticDuke");
try {
// performer.perform();
performer1.perform();
} catch (PerformanceException e) {
e.printStackTrace();
}
}
}

  5 执行结果如下

一月 ,  :: 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35bf8de1: startup date [Sat Jan :: CST ]; root of context hierarchy
一月 , :: 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
一月 , :: 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3401a0ad: defining beans [duke,sonnet29,poeticDuke]; root of factory hierarchy
Juggler beanBags
While reciting...
嘛咪嘛咪哄

【Spring实战】—— 2 构造注入的更多相关文章

  1. Spring入门_03_构造注入

    实体类 Student.java package com.umgsai.spring.entity; import java.util.Date; public class Student { pri ...

  2. Spring 设值注入 构造注入 p命名空间注入

    注入Bean属性---构造注入配置方案 在Spring配置文件中通过<constructor-arg>元素为构造方法传参 注意: 1.一个<constructor-arg>元素 ...

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

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

  4. spring 构造注入 异常 Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments

    你可能在做项目的时候,需要在项目启动时初始化一个自定义的类,这个类中包含着一个有参的构造方法,这个构造方法中需要传入一些参数. spring提供的这个功能叫“构造注入”, applicationCon ...

  5. Spring注入值得2种方式:属性注入和构造注入

    Spring是一个依赖注入(控制反转)的框架,那么依赖注入(标控制反转)表现在那些地方了? 即:一个类中的属性(其他对象)不再需要手动new或者通过工厂方法进行创建,而是Spring容器在属性被使用的 ...

  6. Spring接口编程_设值注入和构造注入

    说明: UserManagerImp是设值注入,UserManagerImp2是构造注入 接口不注入,也就是在Spring配置文件中没有接口的<bean>,但是定义的时候是用接口 priv ...

  7. 7.28.1 Spring构造注入还是设置注入

    1. 构造方法注入代码如下:public UserManagerImpl(UserDao userDao) {                                              ...

  8. 【Spring学习笔记-2.1】Spring的设值注入和构造注入

    设值注入: 先通过无参数的构造函数创建一个Bean实例,然后调用对应的setter方法注入依赖关系: 配置文件: <?xml version="1.0" encoding=& ...

  9. spring构造注入

    Sping 结构体系结构4个核心组件 Beans:Bean是包装我们应用程序自定义对象Object的bject存有数据. Core: context在发现建立,维护Bean之间关系所需的一些工具.如资 ...

随机推荐

  1. Java中filter内处理重定向遇到的问题

    这是在Java中filter内处理重定向遇到的问题.本意是写一个做URL rewrite 的filter,来重写URL,同时在处理登陆过程中要杀掉当前session,创建新session来代替. 1. ...

  2. python开头——文件声明 详解

    一.解释器声明 1.声明方式 linux #!/usr/bin/python windowns #!c:/python27/python.exe 放在首行 2.作用 告诉电脑,要用/usr/bin下面 ...

  3. 转: centos系统home下的中文目录改为英文目录

    转自h t t p : / /xugang-1017-126-com.iteye.com/blog/2081845 如果安装了中文版的Cent OS之后,root目录和home目录下会出现中文的路径名 ...

  4. java se系列(三) 顺序语句、if...else、switch、While、do-while、for、break、continue

    1 顺序语句 语句:使用分号分隔的代码称作为一个语句. 注意:没有写任何代码只是一个分号的时候,也是一条语句,称作空语句. 顺序语句就是按照从上往下的顺序执行的语句. 2 判断(if…else) 什么 ...

  5. 使用Verilog描述RTL图

    题目要求 分别用两种方式表达此电路: 1)在一个模块中用两个过程来表达: 2)用顶层文件和例化语句的形式来表达. 给出下面RTL图的verilog描述. 1)纯过程语句描述 2)纯连续赋值语句描述 参 ...

  6. moment.js(moment-in-node.js)获取本月最后一天 不指定

    http://tommyhu.cn/moment-in-nodejs/ //获取本月最后一天 to=using.moment(日期).endOf('month').format("YYYY- ...

  7. hibernate离线查询DetachedCriteria清除上次的查询条件

    1 原例概述 别名重复问题之后,我们还需要解决的问题就是: 如何清除hibernate的上次查询条件,如果不清除,将会导致上次的查询条件和下次的查询条件合并到了一起. 上次的查询条件和本次的查询条件合 ...

  8. TOJ 3635 过山车

    Description RPG girls今天和大家一起去游乐场玩,终于可以坐上梦寐以求的过山车了.可是,过山车的每一排只有两个座位,而且还有条不成文的规矩,就是每个女生必须找 个个男生做partne ...

  9. django(6)model表语句操作、Form操作、序列化操作

    1.model建表操作之创建索引.元数据 # 单表操作,创建表 class User(models.Model): name = models.CharField(max_length=32) ema ...

  10. 洛谷P1941 飞扬的小鸟(背包 dp)

    题意 题目链接 Sol 很显然的dp,设\(f[i][j]\)表示第\(i\)个位置,高度为\(j\)的最小步数 向上转移的时候是完全背包 向下转移判断一下就可以 #include<bits/s ...