Spring入门到精通:第一章 基础入门:2.Spring之HelloWorld

Spring入门到精通:第一章 基础入门:2.Spring之HelloWorld

前言

这一节我们使用Spring框架来编写一个简单的例子,无hello不框架。

环境说明

(1)JDK 1.8

(2)开发工具:IntelliJ IDEA

(3)maven:3.x

一、Spring开发说明

1.1 Spring****使用方式

常见的有3中方式:

(1)jar包方式;

(2)maven/gradle方式;

(2)Spring Boot方式;

这里Spring Boot不是我们这节的重点,所以采用maven的方式进行学习,Spring Boot的方式可以参考另外一个课程**《从零开始学Spring Boot》**

1.2 maven****编码思路说明

(1)创建一个maven project;

(2)在pom.xml文件添加Spring的依赖;

(3)编写一个HelloService;

(4)编写applicationContext.xml配置文件;

(5)编写测试类;

二、Spring之HelloWorld

2.1 新建maven project

新建一个spring-helloworld的maven project

2.2 添加依赖

在pom.xml文件中添加相关依赖,这里我们使用了parent统一管理,那么就在parent进行添加:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>

2.3 编写HelloService

我们编写一个简单的服务类HelloService:

package com.kfit.test;

public class HelloService {

    public void sayHello(){
        System.out.println("hello Spring");
    }

}

2.4 编写Spring配置类

我们编写一个配置文件applicationContext.xml来管理HelloService:

<?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="helloService" class="com.kfit.test.HelloService"></bean>

</beans>

2.5 编写测试类

编写一个测试的类来运行我们的例子吧:

package com.kfit.test;

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

public class App {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        //获取Spring容器中的对象.
        HelloService helloService = ctx.getBean(HelloService.class);
        helloService.sayHello();
    }
}

Run As运行看一下控制台:

hello Spring

说明我们的第一个Spring的小栗子运行成功了,到这里你可能还不是很懂,那么不要紧,在后面我们会更深入的去学习Spring框架。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值