spring通过构造函数注入实现方法分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring通过构造函数注入实现方法分析

  2021-04-02 我要评论

本文实例讲述了spring通过构造函数注入实现方法。分享给大家供大家参考,具体如下:

一 通过构造函数注入

set注入的缺点是无法清晰表达哪些属性是必须的,哪些是可选的,构造注入的优势是通过构造强制依赖关系,不可能实例化不完全的或无法使用的bean。

二 举例

1 Employee

package com.hsp.constructor;
public class Employee {
    private String name;
    private int age;
    public Employee(String name) {
        System.out.println("Employee(String name) 函数被调用..");
        this.name = name;
        this.age = age;
    }    
    public Employee(String name, int age) {
        System.out.println("Employee(String name, int age) 函数被调用..");
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

2 beans.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:context="http://www.springframework.org/schema/context";
        xmlns:tx="http://www.springframework.org/schema/tx";
        xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";>
<!-- 配置一个雇员对象 -->
<bean id="employee" class="com.hsp.constructor.Employee">
<!-- 通过构造函数来注入属性值 -->
<constructor-arg index="0" type="java.lang.String" value="大明" />
</bean>
</beans>

3 App1

package com.hsp.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/constructor/beans.xml");
    Employee ee=(Employee) ac.getBean("employee");
    System.out.println(ee.getName());
  }
}

三 测试结果

Employee(String name) 函数被调用..
大明

希望本文所述对大家java程序设计有所帮助。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们