使用 Eclipse 创建一个Java 项目。按照选项 File -> New -> Dynamic Web Project。项目命名为 spring_test,如下所示: 创建成功后如图:
添加Spring框架知识整理(二)之准备工作 中下载的jar包。 添加从 Spring 框架和通用日志安装目录下面的核心 JAR 文件。如下所示:
commons-logging-1.1.1 spring-aop-4.1.6.RELEASE spring-aspects-4.1.6.RELEASE spring-beans-4.1.6.RELEASE spring-context-4.1.6.RELEASE spring-context-support-4.1.6.RELEASE spring-core-4.1.6.RELEASE spring-expression-4.1.6.RELEASE spring-instrument-4.1.6.RELEASE spring-instrument-tomcat-4.1.6.RELEASE spring-jdbc-4.1.6.RELEASE spring-jms-4.1.6.RELEASE spring-messaging-4.1.6.RELEASE spring-orm-4.1.6.RELEASE spring-oxm-4.1.6.RELEASE spring-test-4.1.6.RELEASE spring-tx-4.1.6.RELEASE spring-web-4.1.6.RELEASE spring-webmvc-4.1.6.RELEASE spring-webmvc-portlet-4.1.6.RELEASE spring-websocket-4.1.6.RELEASE把上文件拷贝到bin目录下,然后build path。如图:
创建一个名为 com.springtest的包。在 项目src 上点击右键,并按照选项:New -> Package,输入包名。 在包 com.springtest下创建 HelloWorld.java 和 MainTest.java 文件。 HelloWorld.java 文件的内容:
package com.springtest; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } }MainTest.java 的内容:
package com.springtest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); } }注:
使用框架 API ClassPathXmlApplicationContext() 来创建应用程序的上下文。这个 API 加载 beans 的配置文件并最终基于所提供的 API,它处理创建并初始化所有的对象,即在配置文件中提到的 beans。使用已创建的上下文的 getBean() 方法来获得所需的 bean。这个方法使用 bean 的 ID 返回一个最终可以转换为实际对象的通用对象。一旦有了对象,你就可以使用这个对象调用任何类的方法。在 src 目录下创建一个 Bean.xml 的配置文件,该文件作为粘合 bean 的粘合剂即类。Beans.xml 用于给不同的 bean 分配唯一的 ID,并且控制不同值的对象的创建,而不会影响 Spring 的任何源文件。
<?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="com.springtest.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>现在可以运行程序看是否打印“Hello World!”
下一篇《Spring框架知识整理(四)之 Spring IoC 容器》
