码迷,mamicode.com
首页 > 编程语言 > 详细

Spring配置构造函数

时间:2015-08-28 11:07:29      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:spring

一:案例截图

技术分享


二:基本代码

Employee.java

<span style="font-size:14px;">package com.sp.constructor;

public class Employee {
	private String name;
	private int age;
	public Employee(){
		System.out.println("无惨构造函数");
	}
	public Employee(String name){
		System.out.println("一个参数构造函数");
		this.name=name;
	}
	<span style="color:#3366ff;">public Employee(String name,int age){
		System.out.println("两个参数的构造函数");
		this.name=name;
		this.age=age;
	}</span>
	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;
	}
}
</span>

三:配置代码

<span style="font-size:14px;"><?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/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置一个雇员对象 -->
<bean id="employee" class="com.sp.constructor.Employee">
	<span style="color:#3366ff;"><!-- 通过构造函数注入属性值 -->
	<!-- 前面其中一个构造函数有两个属性值,所以这里就会自动指向两个参数的构造函数 --></span>
	<constructor-arg index="0" type="java.lang.String" value="Spring"/>
	<constructor-arg index="1" type="int" value="23"/>
</bean>
</beans></span>

四:测试代码

<span style="font-size:14px;">package com.sp.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
	public static void main(String[] args) {
		ApplicationContext ac=new ClassPathXmlApplicationContext("com/sp/constructor/beans.xml");
		Employee ee=(Employee) ac.getBean("employee");
		System.out.println(ee.getName());
	}
}</span>

五:测试结果

两个参数的构造函数
Spring

版权声明:博主原创文章,转载请说明出处。http://blog.csdn.net/dzy21

Spring配置构造函数

标签:spring

原文地址:http://blog.csdn.net/dzy21/article/details/48048561

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!