随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
在类被实例化时,它的构造方法被调用并且只能调用一次。所以构造器常被用于类的初始化操作。<constructor-arg>是<bean>元素的子元素。通过<constructor-arg>元素的<value>子元素可以为构造器传参。
实例如下:
JavaBean对象User:
package com.home.web.dto;
public class User {
private String name;
private Integer age;
private String sex;
public User() {
super();
}
public User(String name, Integer age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public void printInfo() {
System.out.println("用户姓名:" + name);
System.out.println("用户年龄:" + age);
System.out.println("用户性别:" + sex);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
applicationContext.xml:
关于User的配置:
<!-- User Bean -->
<bean name="user" class="com.home.web.dto.User">
<constructor-arg index="0" type="String">
<value>小明</value>
</constructor-arg >
<constructor-arg index="1" type="Integer">
<value>25</value>
</constructor-arg >
<constructor-arg index="2" type="String">
<value>男</value>
</constructor-arg>
</bean>
Manger.java:
package com.home.web.manager;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.home.web.dto.User;
public class Manager {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
User user = (User) factory.getBean("user");
user.printInfo();
}
}