Spring 框架环境搭建

一、环境要求

JDK版本:

JDK1.7及以上版本

Spring版本:

Spring5.x版本

二、新建Maven项目

1. 创建 Maven 的普通 Java 项⽬
2.设置项目坐标
3.设置项目的Maven环境
4.设置项目的名称和存放的工作空间

三、调整项目环境

1.修改JDK版本

properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.target>12</maven.compiler.target>

</properties>

2.修改单元测试JUnit版本

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

<scope>test</scope>

</dependency>

3.build标签中的pluginManagement标签

<!--删除build标签中的pluginManagement标签-->

<build>

</build>

四、添加Spring框架的依赖坐标

Maven仓库:https://mvnrepository.com/

<!-- 添加Spring框架的核⼼依赖 -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>5.2.4.RELEASE</version>

</dependency>

五、编写Bean对象

六、添加Spring配置文件

1.将 resources 标记为资源⽬录
2. 在 src\main\resources ⽬录下新建 spring.xml ⽂件,并拷⻉官⽹⽂档提供的模板内容到 xml 中。

配置 bean 到 xml 中,把对应 bean 纳⼊到 Spring 容器来管理

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

https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--

xmlns 即 xml namespace xml使⽤的命名空间

xmlns:xsi 即xml schema instance xml 遵守的具体规范

xsi:schemaLocation 本⽂档xml遵守的规范 官⽅指定

-->

<bean id="userDao" class="com.xxxx.Dao.UserDao"></bean>

</beans>

3.在 spring.xml 中配置 Bean 对象

<!--
id : bean 对象的 id ,唯⼀标识。⼀般是 Bean 对象的名称的⾸字⺟⼩写
class : bean 对象的类路径
-->

<bean id="userDao" class="com.xxxx.Dao.UserDao"></bean>

七、加载配置文件,获取实例化对象

package com.xxxx;

import com.xxxx.service.UserService;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String\[\] args) {

// 获取Spring上下⽂环境 (加载配置⽂件)

ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");

// 通过getBean⽅法得到Spring容器中实例化好的Bean对象 (实例化Bean对象)

// userDao代表的是配置⽂件中bean标签的id属性值

UserDao userDao = (UserDao ) ac.getBean("userDao ");

// 调⽤⽅法 (使⽤实例化对象)

userDao .test();

}

}

相关推荐
snow@li10 分钟前
Java:跨平台原理与JDK、JRE、JVM全景深度解析
java·开发语言·jvm
覆东流15 分钟前
2.Java程序基础
java·开发语言·后端
snow@li20 分钟前
SpringBoot:全套生命周期全景详解/应用级+Bean级
java·spring boot·rpc
蓝鸟197425 分钟前
Oracle 19c JSON_OBJECT 完全实战指南|嵌套、多行多列数组合并、空值踩坑、医保报文落地
数据库·oracle·json_arrayagg·多行转json数组·sql实战踩坑·数据库json拼装·json_object
晴天1628 分钟前
Agent 全栈学习笔记 1-Day14
数据库·笔记·学习
瀚高PG实验室28 分钟前
几种因网络波动导致应用与数据库操作异常的现象
运维·网络·数据库·postgresql·瀚高数据库
love_muming32 分钟前
二叉树操作全解析:从递归到层序遍历
java·数据结构·算法·二叉树
小的~~33 分钟前
ThreadLocal 、InheritableThreadLocal 与 TransmittableThreadLocal 的进阶指南
java·开发语言
北极糊的狐44 分钟前
钉钉小程序报错data.formatTime is not a function是因为 axml 模板中不能直接调用 Page 内自定义方法!
java·小程序·钉钉
崖边看雾1 小时前
同步上下文管理器规则
开发语言·数据库