实体类:
package org.service;
public class ManService {
int id;
//有参构造器
public ManService(int id) {
super();
id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "ManService [id=" + id + "]";
}
//无参构造器
public ManService() {
super();
}
}
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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<bean id="m1" class="org.service.ManService">
<property name="id" value="99" />
</bean>
<bean id="m2" class="org.service.ManService">
<constructor-arg value="1"></constructor-arg>
</bean>
</beans>
解析:
1 setter注入
当创建一个bean标签时候 比如上面这个id为"m1"的bean标签,他会先调用这个类的无参构造方法,如果没有无参构造方法会直接报错,然后当你通过<property>标签进行赋值的时候会自动调用该属性的set方法,如果没有类里没有set方法,也会报错。
2 构造函数注入
如上图<bean id="m2"> 通过构造函数注入如果<constructor-arg>标签如果有值,会调用有参的构造方法,如果只有类里没有有参的构造函数会报错。