简介
本文介绍如何用 Eclipse 新建一个 Java Spring 最简控制台项目。
步骤
源码:https://github.com/HustLion/java_console_spring
- 新建一个 maven 项目。File->New->Other->Maven->Next->maven-archetype-quickstart->输入group id等->确认生成项目。图文步骤讲解:Eclipse 创建 java maven 的 Hello world 项目
在
pom.xml
中引入 spring-context 依赖<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.8.RELEASE</version> </dependency>
创建
src/main/java/com/hustlion/java_console_spring/HelloWorld.java
文件package com.hustlion.java_console_spring; public class HelloWorld { private String message; public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("Your Message : " + message); } }
创建
src/main/java/Beans.xml
文件<?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,以及对应的 java 类 --> <bean id="helloWorld" class="com.hustlion.java_console_spring.HelloWorld"> <!-- 设置对应的 java 类的成员属性 --> <property name="message" value="Hello World!" /> </bean> </beans>
修改
src/main/java/com/hustlion/java_console_spring/App.java
package com.hustlion.java_console_spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main(String[] args) { // 获取 classpath 中的 Beans.xml 到上下文 context // 此处即 /java_console_spring/src/main/java/Beans.xml ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); // 获取在 Beans.xml 中定义的 id 为 helloWorld 的 bean HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); // 使用获得的 bean 的 getMessage 方法 obj.getMessage(); // 关闭上下文,防止内存泄漏 ((ClassPathXmlApplicationContext) context).close(); } }
运行项目,控制台输出如下:
五月 28, 2017 5:39:56 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Sun May 28 17:39:56 CST 2017]; root of context hierarchy 五月 28, 2017 5:39:56 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [Beans.xml] Your Message : Hello World! 五月 28, 2017 5:39:56 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Sun May 28 17:39:56 CST 2017]; root of context hierarchy