准备工作
- IDEA版本:2020.2
- 相关环境:基础jar包提取码:8cud
创建环节
概览:新建一个普通Java项目——add Frameworks Support——勾选Spring和Web Profile——导入相关jar包
第一步
新建一个项目(New Project)或模块(New Model)
我这里选择新建模块,与新建项目相同
点击Next进入以下界面↓
- Model name: 模块名称 (根据自己情况随意取便可)
- Content root: 内容根目录
👆概念:Content Root是一个包含组成模块(Module)的所有文件的文件夹。
一个模块可以有多个 Content Root ,但是在大多数情况下,一个 Content Root 就足够了。(在某些情况下,没有 Content Root 的模块可能是有用的。) - Model file location: 源文件存放地址
点击Finish创建完成就可以得到一个这样的文件结构↓
第二步
对Demo1右键选择add Frameworks Support然后勾选Spring和Web Profile
点击OK后↓
第三步
在WEB-INF下新建一个lib文件夹 将以下jar包复制进去
随后进入File下的Project Structure点击Demo1选择Dependencies点击+号↓
选中刚刚导入的核心jar包点击OK
点击Apply
这样模块就创建好了
启动测试
项目结构
编写代码
首先创建一个Person类↓
package com.jaolvv.Example;
/**
* Created with IntelliJ IDEA.
*
* @Website : https://www.jaolvv.top
* @Date 3/22/2021 4:51 PM
* @ClassName Person
* @Author Liu
* 注释/说明:
**/
public class Person {
private String name;
private int age;
public Person(){
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
创建一个Spring的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:给配置的类起个后续在容器中获取用的id class:类所在的路径-->
<bean id="Person" class="com.jaolvv.Example.Person"></bean>
</beans>
创建测试类PersonTest↓
package com.jaolvv.Example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created with IntelliJ IDEA.
*
* @Website : https://www.jaolvv.top
* @Date 3/22/2021 4:53 PM
* @ClassName PersonTest
* @Author Liu
* 注释/说明:
**/
public class PersonTest {
public static void main(String[] args) {
//查询类路径 加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/jaolvv/Example/Bean.xml");
//根据id获取Beam
//Spring就是一个大工厂(容器)专门生成bean bean就是对象
Person person = (Person)applicationContext.getBean("Person");
//输出获取到的对象
Person person1 = new Person();
person1.setName("liu");
person1.setAge(21);
System.out.println("Person = " + person1);
}
}
运行结果👇
到这里,一个Spring项目的创建运行就完成了。