Spring简单实例

通过新建java工程小试Spring,对其结构有大概的了解。
(1)新建工程
创建一个新的Java工程,“HelloSpring”

点击菜单“File -> New -> Project”,并选择“Java Project”,创建成功后工程目录结构大致如下:


(2)添加依赖jar包
在工程中添加所许的Spring库(Spring jar包)
在“HelloSpring”工程上单击右键,然后点击菜单“Build Path -> Configure Build Path”,将弹出以下对话框:
这里写图片描述
然后通过“Add External JARs”按钮添加Spring框架所需要的jar包(上图显示的是添加完jar包之后的界面)。
(3)创建Java类
- 新建一个Java包,名为“com.tutorialspoint”。
- 新建一个Java类,名为“HelloWorld”。
其代码如下:


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);
    }
}

再新建一个Java类,名为“MainApp”。其代码如下:

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();
    }
}

(4)创建Spring配置文件
src目录下创建一个Spring配置文件,名称为“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="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

(5)运行程序
运行程序后,控制台上将得到以下结果:

Your Message : Hello World!

(6)Spring程序结构说明
Spring框架实际上是由一组jar包组成,所以利用Spring框架编程实际上就是使用Spring框架中所提供的类编写程序。所以使用Spring框架的程序一般由以下几个部分组成:

用户所编写的程序
用户所编写Spring配置文件
Spring框架(jar包)

Spring程序与普通程序的一个显著的区别在于对象的创建方式。Spring程序中的对象是由Spring框架按照配置文件的要求进行创建,而不是像普通的Java程序一样,在程序中通过new关键字创建。例如上节中的MainApp的创建HelloWorld对象的代码如下:

public static void main(String[] args) {
    ApplicationContext context = 
         new ClassPathXmlApplicationContext("Beans.xml");   
    HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
    obj.getMessage();
}

上面的代码与以下代码等价:

public static void main(String[] args) {
    HelloWorld obj = new HelloWorld();
    obj.getMessage();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值