Springboot項目開發入門:新手必讀指南
Spring Boot项目开发入门主要介绍了从搭建开发环境到创建并运行第一个Spring Boot项目的过程,涵盖了数据库集成、常用注解以及静态资源管理等关键点。此外,文章还详细讲解了如何使用Thymeleaf、JSP和Freemarker等模板引擎。通过这些内容,读者可以快速掌握Spring Boot项目开发的基本技能。
Spring Boot项目开发入门:新手必读指南 Spring Boot简介Spring Boot是什么
Spring Boot 是一个基于Spring框架的快速开发框架,它简化了Spring应用的开发过程。Spring Boot的目标是简化Spring应用的初始配置,并且支持快速构建独立的、生产级别的应用。Spring Boot提供了大量的默认配置,使得开发者可以专注于应用的业务逻辑,而不需要过多关注底层的配置细节。
Spring Boot的优势
- 自动配置:Spring Boot能够自动配置Spring应用,具体行为会根据应用类型、数据源、Servlet容器等因素进行不同设置。
- 约定优于配置:开发者只需要遵循一定的规则,而不需要写大量的配置代码,从而大大降低了开发的复杂度。
- 无需要XML配置:Spring Boot应用很少需要XML配置,大多数配置都可以直接通过注解来完成,甚至可以通过
application.properties
或application.yml
文件来完成。 - 独立运行:可以打包成独立的war或者jar文件,通过
java -jar
命令直接运行,无需额外的web服务器支持。 - 嵌入式Servlet容器:内置了Tomcat、Jetty或Undertow,可以方便地与Servlet容器集成,即可以快速启动一个Web应用。
Spring Boot与Spring的区别
Spring Boot与Spring框架的主要区别在于它们的角色。
- Spring:是一个通用的框架,提供了应用程序需要的基础设施,例如依赖注入、事务管理等。它需要开发者手动配置应用程序的各个组件。
- Spring Boot:是一个基于Spring的快速开发框架,它主要目的是简化Spring应用的开发过程,提供自动配置和约定优于配置的功能,减少开发者的配置工作。
JDK安装与配置
- 下载JDK:访问Oracle官方网站或OpenJDK官方网站,下载JDK的安装包。
- 安装JDK:运行下载的安装程序,按照提示完成安装。
- 配置环境变量:安装完成后,需要配置环境变量
JAVA_HOME
指向JDK安装目录,PATH
变量包含%JAVA_HOME%\bin
路径。 - 验证安装:启动命令行工具,输入
java -version
,如果显示了JDK的版本信息,则安装成功。
示例代码(验证JDK安装):
java -version
IDE选择与设置
- IDE选择:推荐使用IntelliJ IDEA或Eclipse,这两个IDE都提供了良好的Spring Boot支持。
- 安装IntelliJ IDEA:
- 下载并安装IntelliJ IDEA。
- 设置Java SDK:在IntelliJ IDEA中,选择
File
->Project Structure
->SDKs
,点击+
号添加安装好的JDK。
- 安装Spring插件:在IntelliJ IDEA中安装Spring Boot插件,可以通过
Settings
->Plugins
搜索并安装Spring Boot
插件。 - 创建Spring Boot项目:在IntelliJ IDEA中,选择
File
->New
->Project
,然后选择Spring Initializr
,选择Spring Boot版本和项目类型,点击Next
,输入项目名称和位置,点击Finish
完成项目创建。
示例代码(Spring插件配置):
<!-- 示例配置,实际配置可能需要根据IDEA版本和插件版本进行调整 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
Maven与Gradle简介
- Maven简介:
- Maven是一个项目管理工具,可以管理Java项目的构建、依赖关系和文档。
- Maven使用
pom.xml
文件来描述项目的配置信息。
- Gradle简介:
- Gradle是一个基于Apache Ant和Apache Maven概念的构建工具,具备了两者所有优点。
- Gradle使用
build.gradle
文件来描述项目的配置信息。
示例代码(maven项目配置):
<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.example</groupId>
<artifactId>demo</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
示例代码(gradle项目配置):
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '1.0.0'
repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web')
}
第一个Spring Boot项目
创建Spring Boot项目
- 创建项目:打开IntelliJ IDEA,选择
File
->New
->Project
,然后选择Spring Initializr
,选择项目类型为Spring Starter Project
。 - 选择项目配置:选择Spring Boot版本和项目依赖,这里可以选择
Web
依赖,然后点击Next
。 - 输入项目信息:输入项目名称,点击
Finish
完成项目创建。
添加依赖
- pom.xml配置:在Spring Boot项目中,可以在
pom.xml
文件中添加所需的依赖项。spring-boot-starter-web
:提供了Spring Boot应用的基本Web功能。
- build.gradle配置:在使用Gradle构建的Spring Boot项目中,可以在
build.gradle
文件中添加依赖项。implementation('org.springframework.boot:spring-boot-starter-web')
:提供了Spring Boot应用的基本Web功能。
示例代码(pom.xml添加依赖):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
示例代码(build.gradle添加依赖):
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web')
}
主程序类编写
- 创建主程序类:在项目中创建一个主程序类,该类需要使用
@SpringBootApplication
注解。 - 启动应用:在主程序类中定义一个
main
方法,使用SpringApplication.run
方法启动应用。
示例代码(创建主程序类):
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
运行第一个Spring Boot应用
- 运行主程序类:在IDE中,右键点击主程序类的
main
方法,选择Run
运行应用。 - 访问应用:打开浏览器,访问
http://localhost:8080
,应该能看到默认的欢迎页面。
@SpringBootApplication
@SpringBootApplication
是一个复合注解,包含了@SpringBootConfiguration
、@EnableAutoConfiguration
和@ComponentScan
三个注解。@SpringBootConfiguration
:标记该类为配置类。@EnableAutoConfiguration
:启用自动配置功能。@ComponentScan
:扫描并注册标记为@Component
的类。
示例代码(使用@SpringBootApplication):
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Controller, @Service, @Repository, @Component
- @Controller:标记该类为控制器,Spring Boot会自动扫描控制器并注册到Spring容器中。
- @Service:标记该类为服务层,Spring Boot会自动扫描服务层并注册到Spring容器中。
- @Repository:标记该类为数据访问层,Spring Boot会自动扫描数据访问层并注册到Spring容器中。
- @Component:标记该类为通用组件,Spring Boot会自动扫描所有标记为
@Component
的类并注册到Spring容器中。
示例代码(使用@Controller):
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}
示例代码(使用@Service):
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public String sayHello() {
return "Hello Service";
}
}
示例代码(使用@Repository):
package com.example.demo.repository;
import org.springframework.stereotype.Repository;
@Repository
public class DemoRepository {
public String sayHello() {
return "Hello Repository";
}
}
示例代码(使用@Component):
package com.example.demo;
import org.springframework.stereotype.Component;
@Component
public class DemoComponent {
public String sayHello() {
return "Hello Component";
}
}
@Autowired, @Qualifier
- @Autowired:自动装配依赖,Spring Boot会自动在Spring容器中查找匹配的Bean并注入到需要的地方。
- @Qualifier:当同一个接口有多个实现类时,需要使用
@Qualifier
来指定具体的实现类。
示例代码(使用@Autowired):
package com.example.demo.controller;
import com.example.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@Autowired
private DemoService demoService;
@GetMapping("/hello")
public String hello() {
return demoService.sayHello();
}
}
示例代码(使用@Qualifier):
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
@Autowired
@Qualifier("demoRepository1")
private DemoRepository demoRepository;
public String sayHello() {
return demoRepository.sayHello();
}
}
示例代码(使用@Qualifier的实现类):
package com.example.demo.repository;
import org.springframework.stereotype.Repository;
@Repository("demoRepository1")
public class DemoRepository1 implements DemoRepository {
@Override
public String sayHello() {
return "Hello Repository1";
}
}
@Repository("demoRepository2")
public class DemoRepository2 implements DemoRepository {
@Override
public String sayHello() {
return "Hello Repository2";
}
}
@RequestMapping, @GetMapping, @PostMapping
- @RequestMapping:映射HTTP请求到控制器的方法,可以指定请求类型(GET、POST等)。
- @GetMapping:映射GET请求到控制器的方法。
- @PostMapping:映射POST请求到控制器的方法。
示例代码(使用@RequestMapping):
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@RequestMapping("/hello")
public String hello() {
return "Hello World";
}
}
示例代码(使用@GetMapping):
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}
示例代码(使用@PostMapping):
package com.example.demo.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@PostMapping("/hello")
public String hello() {
return "Hello World";
}
}
数据库集成
Spring Boot与MyBatis集成
- 添加依赖:在项目中添加MyBatis的依赖。
- 配置MyBatis:在
application.properties
或application.yml
文件中配置数据库连接信息。 - 编写Mapper接口:定义与数据库交互的接口,使用
@Mapper
注解标记该接口。 - 编写SQL映射文件:在
resources
目录下创建SQL映射文件,定义查询语句。 - 编写Service和Controller:在Service和Controller中调用Mapper接口的方法。
示例代码(添加MyBatis依赖):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
</dependencies>
示例代码(配置数据库连接):
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
示例代码(Mapper接口):
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(Integer id);
}
示例代码(SQL映射文件):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getUserById" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
示例代码(Service和Controller):
package com.example.demo.service;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
}
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Integer id) {
return userService.getUserById(id);
}
}
Spring Boot与JPA集成
- 添加依赖:在项目中添加JPA的依赖。
- 配置数据库连接:在
application.properties
或application.yml
文件中配置数据库连接信息。 - 实体类定义:定义与数据库表对应的实体类,使用
@Entity
注解标记实体类。 - 编写Repository接口:定义与数据库交互的接口,继承
JpaRepository
接口。 - 编写Service和Controller:在Service和Controller中调用Repository接口的方法。
示例代码(添加JPA依赖):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
示例代码(配置数据库连接):
spring.datasource.url=jdbc:mysql://localhost:3306/jpa
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
示例代码(实体类定义):
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// Getter and Setter
}
示例代码(Repository接口定义):
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
示例代码(Service和Controller):
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
}
数据库连接配置
在application.properties
或application.yml
文件中配置数据库连接信息。
示例代码(application.properties配置):
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
示例代码(application.yml配置):
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
实体类与DAO层编写
- 实体类定义:定义与数据库表对应的实体类,使用
@Entity
注解标记实体类。 - DAO层定义:定义与数据库交互的接口,使用
@Repository
注解标记该接口。
示例代码(实体类定义):
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// Getter and Setter
}
示例代码(DAO层定义):
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
静态资源管理和模板引擎
静态资源目录配置
Spring Boot默认提供了静态资源目录的配置,这些目录位于src/main/resources/static
、src/main/resources/public
、src/main/resources/resources
。
示例代码(在application.properties中配置静态资源路径):
spring.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/resources/
Thymeleaf模板引擎入门
- 添加依赖:在项目中添加Thymeleaf的依赖。
- 配置模板位置:默认情况下,Thymeleaf会在
src/main/resources/templates
目录下查找模板文件。 - 编写HTML模板:在模板文件中使用Thymeleaf语法。
- 编写Controller:在Controller中返回Thymeleaf模板。
示例代码(添加Thymeleaf依赖):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
示例代码(HTML模板文件):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Thymeleaf Example</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'"></h1>
</body>
</html>
示例代码(Controller返回Thymeleaf模板):
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String thymeleaf(Model model) {
model.addAttribute("name", "World");
return "hello";
}
}
使用JSP与Freemarker
JSP
- 添加依赖:在项目中添加JSP的依赖。
- 配置JSP资源路径:默认情况下,JSP文件位于
src/main/webapp/WEB-INF/views
目录下。 - 编写JSP页面:在JSP页面中使用JSTL标签库。
- 编写Controller:在Controller中返回JSP页面。
示例代码(添加JSP依赖):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
示例代码(JSP页面文件):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Spring Boot JSP Example</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
</body>
</html>
示例代码(Controller返回JSP页面):
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class JspController {
@GetMapping("/jsp")
public String jsp(Model model) {
model.addAttribute("name", "World");
return "jsp/hello";
}
}
Freemarker
- 添加依赖:在项目中添加Freemarker的依赖。
- 配置Freemarker资源路径:默认情况下,Freemarker模板文件位于
src/main/resources/templates
目录下。 - 编写Freemarker模板:在Freemarker模板文件中使用Freemarker语法。
- 编写Controller:在Controller中返回Freemarker模板。
示例代码(添加Freemarker依赖):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
示例代码(Freemarker模板文件):
<!DOCTYPE html>
<html>
<head>
<title>Spring Boot Freemarker Example</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
</body>
</html>
示例代码(Controller返回Freemarker模板):
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FreemarkerController {
@GetMapping("/freemarker")
public String freemarker(Model model) {
model.addAttribute("name", "World");
return "hello";
}
}
总结
通过以上章节的介绍,我们已经了解了如何从零开始搭建一个Spring Boot开发环境,创建并运行第一个Spring Boot项目,并学习了Spring Boot常用的注解,以及如何集成数据库和使用模板引擎Thymeleaf、JSP和Freemarker。希望这些内容能帮助你快速入门Spring Boot开发,并为你的项目开发打下坚实的基础。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章