/** * @author zhangzhixi */ public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ‘}‘; } }
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 使用Spring创建对象,在Spring中这些都称为Bean id:标识单个bean定义的字符串 class:完全限定的类名 property:相当于对象中的属性 name:属性id value:属性值 ref:引用spring容器中创建好的对象 --> <bean id="user" class="com.zhixi.pojo.User"> <property name="id" value="2018"/> <property name="name" value="张志喜"/> </bean> </beans>
public class MyTest { public static void main(String[] args) { // 获取Spring上下文对象,多个xml文件,用逗号隔开 ApplicationContext context = new ClassPathXmlApplicationContext("bens.xml"); // 我们的对象都在spring中进行管理,需要使用的直接去spring容器中取 User user = (User) context.getBean("user"); System.out.println(user.toString()); } }
User{id=2018, name=‘张志喜‘}
原文:https://www.cnblogs.com/zhangzhixi/p/14220496.html