首先从官网下载Spring核心包,本例使用5.0.6,Eclipse
然后创建一个动态web应用SpringDemo1,在/WEB-INF/lib/ 下导入下载的Spring libs目录下的所有包(不知道哪些包具体有什么用,所以全部导入,避免遗漏)
在src目录下创建com.bean包,并在该目录下创建类Phone和测试类Meg,代码如下:
package com.bean;
public class Phone {
private String brand;
private String price;
private String model;
public void setBrand(String brand) {
this.brand = brand;
}
public void setPrice(String price) {
this.price = price;
}
public void setModel(String model) {
this.model = model;
}
public String getBrand() {
return brand;
}
public String getPrice() {
return price;
}
public String getModel() {
return model;
}
}
package com.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Meg {
public static void main(String[] args) {
ApplicationContext sc = new ClassPathXmlApplicationContext("applicationContext.xml");
Phone phone=(Phone)sc.getBean("phone");
System.out.println("品牌: "+phone.getBrand());
System.out.println("价格:"+phone.getPrice());
System.out.println("型号:"+phone.getModel());
}
}
然后在src目录下创建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.xsd">
<bean id="phone" class="com.bean.Phone">
<property name="brand" value="苹果"></property>
<property name="price" value="8848"></property>
<property name="model" value="iphonex"></property>
</bean>
</beans>
不会创建可以参考官网:https://docs.spring.io/spring/docs/5.0.6.BUILD-SNAPSHOT/spring-framework-reference/core.html#beans-basics
右键点击Meg,运行方式,Java应用程序,运行成功显示: