Spring赋值有多种方法下面来介绍几种:
首先创建项目:
创建类User:
public class User {
private int id;
private String name;
private String password;
public User(int id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
}
创建方法创建:applictionContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 设值注入 -->
<bean class="com.sxt.pojo.User" >
<constructor-arg name="id" value="03"></constructor-arg>
<constructor-arg name="name" value="03name"></constructor-arg>
<constructor-arg name="password" value="03password"></constructor-arg>
</bean>
</beans>
创建Demo类:
public class Demo {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applictionContext.xml");
User user=ac.getBean(User.class);
// user.toString();
System.out.println(user);
}
导包:
执行后可以给User赋值: