第一个Spring程序(ApplicationContext 容器)

首先创建两个类,HelloWorld.java和MainApp.java

HelloWorld.java用来创建具体的类对象,

MainApp.java用来执行操作。

然后要创建xml的配置文件映射spring框架和项目。

当然,首先要把spring框架的lib导入项目中。

以下是三个文件的具体代码:

 

 

package test;

public class HelloWorld {
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		System.out.println("Your Message :"+message);
	}
	

}

  

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String[] args) {
		//通过xml文件生成bean
		ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");//通过配置classpath确定的xml文件位置
		HelloWorld obj = (HelloWorld)context.getBean("helloworld");//根据bean的id获取bean,再强转为要操作的类型
		obj.getMessage();
	}

}

  

 

  

<?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-3.0.xsd">

   <bean id="helloworld" class="test.HelloWorld">
       <property name="message" value="你好世界!"/>
   </bean>

</beans>

 

posted on 2018-03-09 13:26  三盛乙烯  阅读(162)  评论(0编辑  收藏  举报

导航