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框架。