ITPub博客

首页 > IT职业 > IT生活 > 第一个spring程序:spring hello world

第一个spring程序:spring hello world

IT生活 作者:danielliu 时间:2021-09-09 09:39:24 0 删除 编辑

我们这个系列使用的spring版本是3.0,这是系列的第一篇文章,介绍如何使用spring创建一个java bean,输出hello world

我使用的开发工具是spring的spring tool suit,这是一个基于eclipse的免费开发工具,你可以到spring的官方网站下载他。

另外我们的示例项目都是maven项目。

首先请打开sts(spring tool suit),并新建一个maven项目,在pom.xml中添加spring依赖项:

 
 4.0.0 
 
 cn.outofmemory 
 spring-hello-world 
 0.0.1-SNAPSHOT 
 jar 
 
 spring-hello-world 
 http://maven.apache.org 
 
  
 UTF-8 
 3.0.5.RELEASE 
  
 
  
 <!-- Spring framework --> 
  
 org.springframework 
 spring-context 
 ${spring.version} 
  
  

 其中${spring.version}在properties节点中定义,我们使用的版本是3.0.5.RELEASE。

这样项目中就添加了spring-context包的依赖,我们这个示例要在spring配置文件中初始化一个Hello对象,并在main方法中调用一下Hello对象的sayHello方法。

我们先看下Hello类的代码:

package cn.outofmemory.spring; public class Hello { public void sayHello() { System.out.println("hello spring"); } }

有了hello类我们就可以在spring配置文件中添加spring的bean定义了,我们需要添加一个source folder,命名为src/main/conf,然后在其下建立spring.xml文件。

文件内容如下:

 
 
  

配置文件beans节点中的内容是spring的命名空间定义和schema的定义,真正我们自己写的就是bean节点,这里我们只是指定了bean的class属性,即指定了bean的类型。

下面我们看下,如何使用Bean,下面是App类的代码:

package cn.outofmemory.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /**  * Hello world!  *  */ public class App  {     public static void main( String[] args )     {         ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml");         Hello hello = appContext.getBean(Hello.class);         hello.sayHello();     } }

在main方法中有三行代码:

  1. 第一行初始化了一个ApplicationContext实例,这里我们用的是ClassPathXmlApplicationContext,构造函数的参数是spring配置文件在资源文件中的路径。

  2. 第二行代码通过appContext的getBean方法获得Hello bean的实例

  3. 第三行代码调用了hello的sayHello方法

运行代码,将输出hello spring。

是不是很简单?下一篇我们来看下spring的伟大意义。

下载源码:spring-hello-world.zip

原文链接:http://outofmemory.cn/java/spring/spring-hello-world

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/866/viewspace-2811206/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    119
  • 访问量
    808