一、建立一个java工程文件,目录如下
lib是我自己建立的,存放我需要的jar包
二、HelloWorld.java
package spring; public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public void hello(){ System.out.println("hello"+name); } } 三、Main.java
package spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub // 1.创建spring的IOC容器对象 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationcontext.xml"); // 2.从IOC容器中获取bean实例 HelloWorld helloWorld=(HelloWorld)ctx.getBean("helloworld"); // 3.调用hello方法 helloWorld.hello(); } } 四、applicationcontext.xml,注意这个文件是建立在src包下,如果错了,就找不到 <?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="helloworld" class="spring.HelloWorld"> <property name="name" value="diyunlong"></property> </bean> </beans> 运行结果: