编写User.java
1 package com.example.spring; 2 3 public class User { 4 private String name; 5 private Integer age; 6 private String country; 7 8 public User(String name, Integer age, String country) { 9 this.name = name; 10 this.age = age; 11 this.country = country; 12 } 13 14 public String toString() { 15 return name + " is " + age + " years old, living in " + country; 16 } 17 }
编写Beans.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="user" class="com.example.spring.User" > 7 <constructor-arg name="name" type="java.lang.String" value="Jacky" /> 8 <constructor-arg name="age" type="java.lang.Integer" value="22"/> 9 <constructor-arg name="country" type="java.lang.String" value="China"/> 10 </bean> 11 12 </beans>
编写Application.java
package com.example.spring; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { public static void main(String[] args) { //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml //使用AbstractApplicationContext容器 AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml"); User user = (User)context.getBean("user"); System.out.println(user); } }
运行输出
Jacky is 22 years old, living in China
时间: 2024-10-08 19:05:39