Spring项目基础搭建
-
在自己的项目文件目录下新建一个文件夹作为我们的项目根目录,使用IDEA打开这个空目录,这里我的目录名为
sp
-
选中项目右键新建模块选中maven直接下一步空新建
-
点击file->project structure->facets 选中spring添加web,加入
webapp
目录,并且路径修改成webapp 前面并且加上src\main
-
打开pom.xml配置Spring Context,可以直接https://mvnrepository.com/中搜索直接粘贴到pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wang</groupId>
<artifactId>spring</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
</project>
- 如果第一次配置报出红色可点击maven更新
- 到此我们的基础框架搭建完毕,下面进行运用
Spring的简单使用
-
我们跟以前一样简单的穿件dao层然后进行Spring方式进行调用
-
右键resources新建一个名叫applicationContext的xml文件,并配置刚刚的dao实现类
- 创建main进行调用使用
package com.wang.main;
import com.wang.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("UserDao");
userDao.User();
}
}