1 配置好Spring环境
2 在applicationContext.xml中添加Bean配置
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
- "">
- <beans>
- <bean id="HelloWorld" class="com.demo.spring.test.HelloWorld">
- <property name="message">
- <value>World</value>
- </property>
- </bean>
- </beans>
3 新建Bean类---HelloWorld.java
- package com.demo.spring.test;
- public class HelloWorld {
- protected String message;
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public String execute(String str) {
- return "Hello " + getMessage();
- }
- }
3 运行测试类 Test.java
编写测试类Test.java 首先使用FileSystemXmlApplicationContext来读取XML配置文件applicationContext 返回ApplicationContext类型的变量ctx 使用ctx的getBean()函数取得配置的Bean对象 HelloWorld 该名称是XML文件中的配置Bean名称 取得的对象经过强制类型转换为HelloWorld类型 命名为hello 调用hello的execute()执行输出
- package com.demo.spring.test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.FileSystemXmlApplicationContext;
- public class Test {
- public static void main(String[] args) {
- ApplicationContext ctx = new FileSystemXmlApplicationContext(
- "WebRoot/WEB-INF/applicationContext.xml");
- HelloWorld hello = (HelloWorld) ctx.getBean("HelloWorld");
- System.out.println(hello.execute("World"));
- }
- }
运行该程序 如果输出 Hello World 则表示环境已经支持Spring了
输出结果
- INFO - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@18fef3d: display name [org.springframework.context.support.FileSystemXmlApplicationContext@18fef3d]; startup date [Thu Dec 29 21:39:14 CST 2011]; root of context hierarchy
- INFO - Loading XML bean definitions from file [F:\eeeeeee\SpringTest\WebRoot\WEB-INF\applicationContext.xml]
- INFO - Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@18fef3d]: org.springframework.beans.factory.support.DefaultListableBeanFactory@64dc11
- INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@64dc11: defining beans [HelloWorld,viewResolver,testMapping,testAction]; root of factory hierarchy
- Hello World
阅读(5337) | 评论(0) | 转发(0) |