在XML中可使用两种方式进行注入:构造函数注入和setter注入
构造函数注入constructor
直接传值
applicationContext.xml
<bean id="helloworldBeanId" class="com.ssm.beans.HelloWorld">
<constructor-arg name="username" value="YEN"/>
<constructor-arg name="password" value="123"/>
</bean>
HelloWorld.java
public class HelloWorld {
private String username;
private String password;
public HelloWorld(){
}
public HelloWorld(final String username,final String password){
this.username=username;this.password=password;
}
public void show(){
System.out.println("username:"+username+" password:"+password);
}
}
HelloWorldTest.java
public class HelloWorldTest {
public static void main(String[] args) {
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld= (HelloWorld) factory.getBean("helloworldBeanId");
helloWorld.show();
}
}
根据索引赋值
更改applicationContext.xml
<bean id="helloworldBeanId" class="com.ssm.beans.HelloWorld">
<constructor-arg name="username" value="YEN" index="0"/>
<constructor-arg name="password" value="123" index="1"/>
</bean>
根据所属类型传值
<bean id="helloworldBeanId" class="com.ssm.beans.HelloWorld">
<constructor-arg name="username" value="YEN" type="java.lang.String"/>
<constructor-arg name="age" value="123" type="java.lang.Integer"/>
</bean>
此时如果属性类型一样就很容易混乱
setter注入
直接注入
<bean id="helloworldBeanId" class="com.ssm.beans.HelloWorld">
<property name="username" value="YEN"/>
<property name="password" value="123"/>
</bean>
直接注入
<bean id="helloworldBeanId" class="com.ssm.beans.HelloWorld">
<property name="username">
<value>YEN</value>
</property>
<property name="password">
<value>123</value>
</property>
</bean>
<bean id="helloworldBeanId" class="com.ssm.beans.HelloWorld" p:username="YEN" p:password="123"/>
用Setter注入时需要有无参构造函数。