用setter方法实现依赖注入
1.所需jar包
commons-logging-1.0.4.jar
spring.jar
2.实体类User.java
package entity;
public class User {
private String name;
private Integer age;
private String sex;
//setter注入
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;
}
}
3.测试类Test.java
package main;
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 entity.User;
public class Test {
public static void main(String[] args) {
// 导入src下的applicationContext.xml配置文件
Resource resource=new ClassPathResource("applicationContext.xml");
//读取配置文件
BeanFactory factory=new XmlBeanFactory(resource);
//获取bean
User user = (User)factory.getBean("user");
//调用get方法获取xml中配置的实体类属性值
System.out.println(user.getName());
System.out.println(user.getAge());
System.out.println(user.getSex());
}
}
4.配置文件web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>springSetter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
5.配置文件applicationContext.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-2.5.xsd">
<!--配置 User Bean -->
<!-- bean标签的name属性为小写实体类名,class属性为实体类全名(包名+类名) -->
<!-- bean的id和name属性都可以指定bean名 -->
<bean id="user" name="user" class="entity.User">
<!-- 配置属性 -->
<!-- property标签的name属性与实体类中的属性一致 -->
<!-- value标签可以设置实体类中属性的值 -->
<property name="name" >
<value>小强</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="sex" value="男" />
</bean>
</beans>
6.运行效果