Spring学习(一)-Spring入门示例

本文介绍了如何在Eclipse中创建依赖Jar包库,并通过一个简单的Spring入门示例展示了如何使用Spring框架进行开发。示例包括创建Maven项目、定义HelloWorld类、配置XML文件以及创建运行类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从本篇博客开始,后续将重点学习Spring,并记录学习过程中的点点滴滴。
开发环境:jdk 1.7,Eclipse Mars, Spring Framwork 4.3.0
1、 在Eclipse中创建自己的依赖Jar包库
在进行spring开发时,spring框架提供的许多依赖包,在每次新建一个Project后,均需要将这些依赖包导入工程中。Eclipse提供了一个很方便的功能:创建user library,将spring开发需要的依赖包全部放入自定义的user library中。
步骤如下:
(1)点击eclipse的window菜单,选择“Preferences”;
(2)在Preferences中选择Java->Bulid Path->User Libraries,然后点击窗口右边的New按钮,在弹出的子窗口中输入user library的名称,比如spring;
(3)点击Add External JARs,弹出窗口,将spring框架的依赖包添加进去。
这里写图片描述
这里写图片描述
这里写图片描述
创建好用户依赖库spring后,下面介绍如何创建spring的入门示例。

2、Spring的入门示例
先直接给出Spring的一个简单工程实例,下一篇博客再重点介绍Spring的框架。
新建一个mavean工程,工程目录结构为:
这里写图片描述
导入user library spring依赖库
右键Project名称->Build Path ->Add Libraries..,选择User Library,就会看到spring库

创建HelloWorld类

package com.wygu.spring_hello;

public class HelloWorld {
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void printHello() {
        System.out.println("Welcome Spring 4.3.0 !! " + this.getName()+":"+this.getAge());
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

}

定义XML配置文件applicationContext.xml,放置在xml文件夹中

<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-4.3.xsd">

    <bean id="helloBean" class="com.wygu.spring_hello.HelloWorld">
        <property name="name" value="wygu" />
        <property name="age" value="17" />
    </bean>

</beans>

创建运行类APP

package com.wygu.spring_hello;

/**
 * Hello world!
 *
 */
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class APP {

    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml"); 
        HelloWorld obj = (HelloWorld) context.getBean("helloBean");
        obj.printHello();
    }
}

如果直接运行会报错:
这里写图片描述
原因是由于在类APP中加载不到applicationContext.xml
解决方法:
右击xml,选择Build Path->Use as Source Folder
工程运行结果为:
Welcome Spring 4.3.0 !! wygu:17

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值