可以在配制文件中进行实例化,但有时更希望可以在对象实例化时通过构造方法实例化。
Bean中增加一个构造方法。那么就要在配置文件中增加一个参数constrator-org,
例如:
//此方法中有一个构造函数,
package spring02;
public class SimpleBean {
private String name ;
private String password ;
public SimpleBean(String name,String password)
{
this.setName(name) ;
this.setPassword(password) ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
==========================================
//上面用到了构造函数,这里就要用<constructor-arg index="0">
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="simple" class="spring02.SimpleBean">
<constructor-arg index="0">
<value>朱庆良</value>
</constructor-arg>
<constructor-arg index="1">
<value>123456</value>
</constructor-arg>
</bean>
</beans>
===============================================
//测试
package spring02;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = null ;
context = new ClassPathXmlApplicationContext("applicationContext.xml") ;
SimpleBean simple = (SimpleBean)context.getBean("simple") ;
System.out.println("姓名:"+simple.getName()) ;
System.out.println("密码:"+simple.getPassword()) ;
}
}