spring入门------setter注入

用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.运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThinkPet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值