1.设值注入
使用该方法时Bean类必须要有一个无参构造方法,并且Bean类必须为属性提供setter方法
在配置文件中,使用<property>元素来为每个属性注入值。
Bean类示例代码如下:
package com.assemble;
import java.util.List;
public class User {
private String username;
private String password;
private List<String> list;
public User(String username, String password, List<String> list) {
super();
this.username = username;
this.password = password;
this.list = list;
}
public User() {
super();
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", list=" + list + "]";
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 2.使用设值注入方式装配User实例 -->
<bean id="user2" class="com.assemble.User">
<property name="username" value="张三"></property>
<property name="password" value="123456"></property>
<property name="list">
<list>
<value>"setlistvalue01"</value>
<value>"setlistvalue02"</value>
</list>
</property>
</bean>
</beans>
2.构造注入
使用该方法Bean类必须提供有参构造方法,配置文件中使用<constructor-arg>元素来为参数注入值。
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 1.使用构造注入方式装配User实例 -->
<bean id="user1" class="com.assemble.User">
<constructor-arg index="0" value="tom"></constructor-arg>
<constructor-arg name="password" value="123456"></constructor-arg>
<constructor-arg name="list">
<list>
<value>"constructorvalue01"</value>
<value>"constructorvalue02"</value>
</list>
</constructor-arg>
</bean>
</beans>
测试是否注入成功:
package com.assemble;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
public static void main(String[] args) {
//定义配置文件路径
String xmlPath = "com/assemble/bean5.xml";
//ClassPathXmlApplicationContext在加载配置文件时,对Bean进行实例化
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean("user1"));
System.out.println(applicationContext.getBean("user2"));
}
}
运行结果:
成功装配。