applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="fru" class="cn.mldn.lxh.demo01.Orange"></bean>
<bean id="simple" class="cn.mldn.lxh.demo02.SimpleBean">
<constructor-arg index="0">
<value>LiXingHua</value>
</constructor-arg>
<constructor-arg index="1" value="www.MLDN.cn"></constructor-arg>
</bean>
</beans>
=======================================
SimpleBean.java
package cn.mldn.lxh.demo02;
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;
}
}
=================================================
TestDemo03.java
package cn.mldn.lxh.demo02;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDemo03 {
/**
* @param args
*/
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()) ;
}
}
====================================================
虽然在程序中提倡使用POJO类,可是有些时候更希望可以在对象实例化时通过构造方法实例化
通过在配置中增加一个参数,同时Bean中增加一个构造方法
在Spring中如果需要使用构造,则加入constrator-arg元素进行配置
Spring Ioc 技术(constructor-arg )
最新推荐文章于 2024-02-02 14:18:50 发布