Spring 简明教程
Spring - Hello World Example
我们开始使用 Spring Framework 进行实际编程。在使用 Spring 框架编写第一个示例之前,你必须确保已正确设置 Spring 环境,如 Spring - Environment Setup 章节中所述。我们还假设你对 Eclipse IDE 有点了解。
Let us start actual programming with Spring Framework. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring - Environment Setup Chapter. We also assume that you have a bit of working knowledge on Eclipse IDE.
现在让我们开始编写一个简单的 Spring 应用程序,它将打印“Hello World!”或任何其他基于 Spring Bean 配置文件中所做的配置的消息。
Now let us proceed to write a simple Spring Application, which will print "Hello World!" or any other message based on the configuration done in Spring Beans Configuration file.
Step 1 - Create Java Project
第一步是使用 Eclipse IDE 创建一个简单的 Java 项目。遵循选项 File → New → Project ,最后从向导列表中选择向导 Java Project 。现在使用向导窗口将你的项目命名为 HelloSpring ,如下所示:
The first step is to create a simple Java Project using Eclipse IDE. Follow the option File → New → Project and finally select Java Project wizard from the wizard list. Now name your project as HelloSpring using the wizard window as follows −
一旦你的项目成功创建,你将在 Project Explorer 中看到以下内容:
Once your project is created successfully, you will have the following content in your Project Explorer −
Step 2 - Add Required Libraries
作为第二步,让我们在项目中添加 Spring Framework 和通用日志记录 API 库。为此,右键单击你的项目名称 HelloSpring ,然后遵循上下文菜单中提供的以下选项 Build Path → Configure Build Path ,以按如下所示显示 Java 构建路径窗口:
As a second step let us add Spring Framework and common logging API libraries in our project. To do this, right-click on your project name HelloSpring and then follow the following option available in the context menu − Build Path → Configure Build Path to display the Java Build Path window as follows −
现在使用 Libraries 选项卡下的 Add External JARs 按钮从 Spring Framework 和 Common Logging 安装目录中添加以下核心 JAR:
Now use Add External JARs button available under the Libraries tab to add the following core JARs from Spring Framework and Common Logging installation directories −
-
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
Step 3 - Create Source Files
现在让我们在 HelloSpring 项目下创建实际源文件。首先,我们需要创建一个名为 com.tutorialspoint 的包。为此,右键单击包资源管理器部分中的 src ,然后按照以下选项进行操作: New → Package 。
Now let us create actual source files under the HelloSpring project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package.
接下来,我们将在 com.tutorialspoint 包下创建 HelloWorld.java 和 MainApp.java 文件。
Next we will create HelloWorld.java and MainApp.java files under the com.tutorialspoint package.
以下是 HelloWorld.java 文件的内容 −
Here is the content of HelloWorld.java file −
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
以下是第二个文件 MainApp.java 的内容:
Following is the content of the second file MainApp.java −
package com.tutorialspoint;
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();
}
}
关于主程序,需要注意以下两点:
Following two important points are to be noted about the main program −
-
The first step is to create an application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file.
-
The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method.
Step 4 - Create Bean Configuration File
你需要创建一个 Bean 配置文件,它是一个 XML 文件,充当将 Bean(即类)粘合在一起的水泥。需要在 src 目录下创建此文件,如下面的屏幕截图所示:
You need to create a Bean Configuration file which is an XML file and acts as a cement that glues the beans, i.e. the classes together. This file needs to be created under the src directory as shown in the following screenshot −
通常开发人员将此文件命名为 Beans.xml ,但你可以自由选择任何你喜欢的名称。你必须确保此文件在 CLASSPATH 中可用,并在创建应用程序上下文时在主应用程序中使用相同名称,如 MainApp.java 文件中所示。
Usually developers name this file as Beans.xml, but you are independent to choose any name you like. You have to make sure that this file is available in CLASSPATH and use the same name in the main application while creating an application context as shown in MainApp.java file.
Beans.xml 用于为不同的 bean 分配唯一 ID,并控制在不影响任何 Spring 源文件的情况下创建具有不同值的对象。例如,使用以下文件,你可以为“message”变量传递任何值,并且可以在不影响 HelloWorld.java 和 MainApp.java 文件的情况下打印消息的不同值。让我们看看它是如何工作的。
The Beans.xml is used to assign unique IDs to different beans and to control the creation of objects with different values without impacting any of the Spring source files. For example, using the following file you can pass any value for "message" variable and you can print different values of message without impacting HelloWorld.java and MainApp.java files. Let us see how it works −
<?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.tutorialspoint.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
当 Spring 应用程序加载到内存中时,Framework 利用上述配置文件创建定义的所有 bean,并根据 <bean> 标记中定义的内容为它们分配一个唯一 ID。你可以使用 <property> 标记来传递在创建对象时使用的不同变量的值。
When Spring application gets loaded into the memory, Framework makes use of the above configuration file to create all the beans defined and assigns them a unique ID as defined in <bean> tag. You can use <property> tag to pass the values of different variables used at the time of object creation.
Step 5 - Running the Program
一旦你完成了源和 bean 配置文件的创建,你就可以进行此步骤,即编译和运行你的程序。为此,保持 MainApp.Java 文件选项卡处于活动状态,并使用 Eclipse IDE 中提供的 Run 选项或使用 Ctrl + F11 来编译和运行你的 MainApp 应用程序。如果你的应用程序一切正常,它将在 Eclipse IDE 的控制台中打印以下消息:
Once you are done with creating the source and beans configuration files, you are ready for this step, which is compiling and running your program. To do this, keep MainApp.Java file tab active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your MainApp application. If everything is fine with your application, this will print the following message in Eclipse IDE’s console −
Your Message : Hello World!
恭喜你,你已成功创建你的第一个 Spring 应用程序。你可以通过更改“message”属性的值并保持两个源文件不变来查看上述 Spring 应用程序的灵活性。
Congratulations, you have successfully created your first Spring Application. You can see the flexibility of the above Spring application by changing the value of "message" property and keeping both the source files unchanged.