Spring项目简单配置(一)

1.下载Spring框架

  • 从Spring官网下载Spring框架
    根据需要下载不同版本的开发包,我的是4.3.7版本

2.新建项目,导包

  • 新建Web项目 SpringConfig(凭自己喜好命名),将E:\spring-framework-4.3.7.RELEASE\libs(根据自己解压好的文件路径找到对应的目录)下的这些包拷贝到项目的\WEN-INF\lib目录下:
    Spring基本架包

3.建类

  • 创建com.shw包,在包中新建名为HelloWorld的类,代码如下所示:
package com.shw;

public class HelloWorld {
    //定义方法,在控制台输出信息
    public void show() {
        System.out.println("欢迎学习Spring框架");
    }
}

4.配置appcationContext.xml

  • 首先新建appcationContext.xml当然,名字取个见名知意的最好,那么问题来了,该文件里该添加一点什么配置呢?不着急,咱门去官方的文档看看,那里应该会给出例子或具体的配置。
  • spring官网的文档隐藏的有点深,比较难找,如下:
    点击docs

    docs

点击Read the Reference Documentation

refedoc

找到SpringFarmwork,点击Reference

spring

最后到达目的地:

spring

  • 当然你也可以在下载下来的Spring框架找到这目的地:打开E:\spring-framework-4.3.7.RELEASE\docs\spring-framework-reference\htmlsingle目录下的index.html
  • 好吧!废话说了这么多,该开始干正事了,话说咱门说到哪了?对对对,appcationContext.xml的配置,找到Configuration metadata充分利用Google浏览器自带的翻译和Ctrl+F,将图中的内容拷贝到appcationContext.xml中。

spring

如果找不到的话就拷贝下面的吧!

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

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>
  • 将现在不需要的内容去掉,然后填写代码。
<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.xsd">

    <!-- 配置bean,这里主要配置接口的实现类 
       id:给bean取一个名称,方便后面调用,名称不要重复
       class:实现类的完整路径
    -->
    <bean id="haha" class="com.shw.HelloWorld">

    </bean>



</beans>

5.编写测试类

package com.shw;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ProTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 两个参数:参数1:bean的id,跟配置文件中id的值对应   参数2:指定bean的类型
        HelloWorld hw = context.getBean("haha", HelloWorld.class);
        hw.show();
    }
}

当然,这只是比较简单的一个例子,现实中的项目都是操作接口的,比较具体一点的例可以看看GitHub上发布的项目:项目地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值