您的位置:首页 > 编程语言 > Java开发

【spring教程之二】spring注入xml中带参数的构造函数

2015-03-16 20:35 330 查看
1、续上文,如果想在注入bean文件的时候,传入参数到构造函数中。主要需要修改的就是spring.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="do" class="com.test.pro.Student">
<constructor-arg value="19"></constructor-arg>
</bean>
</beans>

2、我们把类修改成了学生类,Student.java,其中没有默认的构造函数,而是一个新的带参数的构造。
package com.test.pro;

public class Student {
private int age;
public Student(int age)
{
this.age=age;
}
public void speaking()
{
System.out.println("我的年龄是:"+age);
}
}


3、输出结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: