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

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

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

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

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

注入属性

  实例代码:

  1 表演者接口:Performer.java

  1. package com.spring.test.action1;
  2.  
  3. public interface Performer {
  4. void perform() throws PerformanceException;
  5. }

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

  1. package com.spring.test.action1;
  2.  
  3. public class Juggler implements Performer{
  4. private int beanBags = ;
  5.  
  6. public Juggler(){
  7.  
  8. }
  9.  
  10. public Juggler(int beanBags){
  11. this.beanBags = beanBags;
  12. }
  13.  
  14. public void perform() throws PerformanceException {
  15. System.out.println("Juggler "+beanBags+" beanBags");
  16. }
  17.  
  18. }

  3 Spring配置文件:bean.xml

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

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

  1. package com.spring.test.action1;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6. public class test {
  7. public static void main(String[] args) {
  8. ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
  9. Performer performer = (Performer)ctx.getBean("duke");
  10. try {
  11. performer.perform();
  12. } catch (PerformanceException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

  执行结果如下:

  1. Juggler beanBags

注入对象

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

  1. package com.spring.test.action1;
  2.  
  3. public class PoeticJuggler extends Juggler{
  4. private Poem poem;
  5.  
  6. public PoeticJuggler(Poem poem){
  7. super();
  8. this.poem = poem;
  9. }
  10.  
  11. public PoeticJuggler(int beanBags,Poem poem){
  12. super(beanBags);
  13. this.poem = poem;
  14. }
  15.  
  16. public void perform() throws PerformanceException {
  17. super.perform();
  18. System.out.println("While reciting...");
  19. poem.recite();
  20. }
  21.  
  22. }

  2 诗歌对象:Sonnet29

  1. package com.spring.test.action1;
  2.  
  3. public class Sonnet29 implements Poem{
  4. private static String lines = "嘛咪嘛咪哄";
  5.  
  6. public Sonnet29() {
  7.  
  8. }
  9.  
  10. public void recite() {
  11. System.out.println(lines);
  12. }
  13.  
  14. }

  3 Bean.xml配置文件如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  6. <bean id="duke" class="com.spring.test.action1.Juggler">
  7. <constructor-arg value=""/>
  8. </bean>
  9. <bean id="sonnet29" class="com.spring.test.action1.Sonnet29"/>
  10. <bean id="poeticDuke" class="com.spring.test.action1.PoeticJuggler">
  11. <constructor-arg value=""/>
  12. <constructor-arg ref="sonnet29"/>
  13. </bean>
  14. </beans>

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

  1. package com.spring.test.action1;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6. public class test {
  7. public static void main(String[] args) {
  8. ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
  9. // Performer performer = (Performer)ctx.getBean("duke");
  10. Performer performer1 = (Performer)ctx.getBean("poeticDuke");
  11. try {
  12. // performer.perform();
  13. performer1.perform();
  14. } catch (PerformanceException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }

  5 执行结果如下

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

【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. SpringMVC 商城项目

    1.  商城视频中有word   笔记文档

  2. PIE.NET-SDK组件式二次开发文档

    一.PIE.Net开发环境及目录说明 1.   开发环境 确保Win7系统已安装SP1 安装Visual Studio2013(支持VS2010/2012/2013/2015) 安装PIESDK.ex ...

  3. linux运维配置讲解--sshd-config

    文件配置: 1, /etc/ssh/sshd_config ssh配置文件 2, /etc/shadow 密码文件 3, /etc/sudoers 授权用户管理文件 4, /etc/issue 系统信 ...

  4. 使用Redis 配置替换fastjson 反序列化报错 com.alibaba.fastjson.JSONException: autoType is not support

    新建的GenericFastJson2JsonRedisSerializer里面添加白名 添加: static {        ParserConfig.getGlobalInstance().ad ...

  5. drupal 7 安装失败后的补救办法

    在安装 drupal 7 时安装,导入数据库已经成功,但是在安装语言包的时候卡住了,没有进行最后三步,管理员帐号没能启用.此时我退出安装,访问网站,没有问题.但是管理员admin的密码没有设置,以至于 ...

  6. 重新分析connection reset by peer, socket write error错误原因

    上次写<connection reset by peer, socket write error问题排查>已经过去大半年,当时把问题"敷衍"过去了. 但是此后每隔一段时 ...

  7. TOJ 4394 Rebuild Road

    描述 Once,in a kingdom,there are N cities.M roads have been buit such that from one city you can reach ...

  8. Nginx实践:(2) Nginx语法之localtion

    1. 概念 location是根据uri进行不同的定位.在虚拟主机的配置中,是必不可少的.location可以将网站的不同部分,定位到不同的处理方式上. location语法格式如下: locatio ...

  9. Find command usage in Linux with excellent examples--reference

    http://www.coolcoder.in/2014/02/find-command-usage-in-linux-with.html find searches the directory tr ...

  10. javascript数组与字符串之间转换

    一.数组转字符串(将数组元素用某个字符连接成字符串) var a, b;a = new Array(0,1,2,3,4);b = a.join("-"); 二.字符串转数组(将字符 ...