1.在搭建好maven项目后(如果不清楚如何搭建maven项目的可以参考我的上一篇博客),项目的目录结构如下图所示:
接下来需要添加spring(用maven管理项目的优点是:1. 借助maven,可以将jar包保存到“仓库”中,有需要使用的工程直接引用相关的包即可,而无需手动复制粘贴到lib下。2.以前的jar包都是提前下好的,如果本地没有还得重新下载,通过maven可以联网下载相关包3.maven可以将一个项目拆分为多个工程,实现“多人开发”)
2.在maven中导入spring框架。
首先去project settings在module 添加spring组件
但是你会在下方看到一个黄色警告。
点击fix
然后下载相应的spring的jar包,即可运行spring框架。
然后你还需要添加依赖jar包可以直接在pom.xml文件右击,点击generate
然后点击Dependency
在搜索框搜索你想要的框架名 ,然后添加即可:
得到如下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
然后我们在src下的main下新建resources文件夹,然后右键文件夹set as root resources,在resources下新建配置文件applicationContext.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.xsd">
<bean id="helloBean" class="com.ray.controller.HelloWorld">
<property name="name" value="RayTseng"/>
</bean>
</beans>
在main文件夹下新建一个java文件夹,然后在java下新建一个包,这里我就随便建了一个包com.ray.controller,然后在该包下面新建两个class文件HelloWorld 以及App文件。
接下来通过这两个class文件,来完成基于spring框架的hello world程序。
public class HelloWorld {
private String name;
public void printHello() {
System.out.println("Spring 4 : Hello ! " + name);
}
public void setName(String name) {
this.name = name;
}
}
package com.ray.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHello();
}
}
运行app.class文件得到,证明spring框架运行成功。