Java类代码如下:
package org.akita.model;
public class User {
private String username;
private String address;
private Integer age;
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
public User(String username, String address, Integer age) {
this.username = username;
this.address = address;
this.age = age;
System.out.println("构造方法被调用");
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
配置文件中属性注入的写法如下:
<bean class="org.akita.model.User" id="user">
<constructor-arg index="0" value="akita"/>
<constructor-arg index="1" value="安徽"/>
<constructor-arg index="2" value="25"/>
</bean>
或者是如下写法
<bean class="org.akita.model.User" id="user">
<constructor-arg name="username" value="akita"/>
<constructor-arg name="address" value="安徽"/>
<constructor-arg name="age" value="25"/>
</bean>
获取User类对象代码如下:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ctx.getBean("user", User.class);
System.out.println(user);
输出如下: