第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

SpringBoot項目開發(fā)學習:從零開始的簡單教程

標簽:
SpringBoot

本文详细介绍了SpringBoot项目开发学习的全过程,包括环境搭建、快速创建第一个项目、核心概念和常用注解的讲解。通过本文,读者可以全面了解并掌握SpringBoot的各项功能和开发技巧。

SpringBoot简介与环境搭建

什么是SpringBoot

SpringBoot是由Pivotal团队提供的框架,旨在简化Spring应用的开发过程。SpringBoot通过提供一系列默认配置,简化了项目配置和依赖管理。它是一个基于Spring框架的独立应用框架,能够快速构建独立的、生产级别的应用。SpringBoot的核心目标是简化开发、部署、测试等流程,使开发者可以专注于业务逻辑的实现。

开发环境搭建

要开始使用SpringBoot进行开发,首先需要完成开发环境的搭建。开发环境主要包括以下几部分:

  1. Java开发环境:SpringBoot基于Java开发,需要先安装Java环境。推荐使用JDK 8及以上版本。
  2. IDE安装:推荐使用IDEA或Eclipse等集成开发环境。
  3. 构建工具:SpringBoot项目通常使用Maven或Gradle进行构建管理。本教程使用Maven来构建项目。
  4. IDE插件:在IDE中安装SpringBoot插件,以获得更好的开发体验。IDEA和Eclipse都有相应的插件支持。

下面是一些具体的步骤来搭建Java开发环境,以确保你可以在本地运行SpringBoot项目:

  1. 下载并安装Java SE

    • 访问Oracle官网Liberica下载Java JDK 11及以上版本。
    • 安装后,确保系统变量JAVA_HOME设置正确,并将%JAVA_HOME%\bin添加到系统PATH中。
  2. 下载并安装IDE

  3. 安装Maven

    • 访问Maven官网下载Maven压缩包。
    • 解压到适当的目录,并将MAVEN_HOME设置为解压后的目录路径。
      .
    • MAVEN_HOME\bin添加到系统PATH中。
  4. 安装Spring Boot插件
    • 在IDEA中,通过File -> Settings -> Plugins,搜索并安装Spring插件。
    • 在Eclipse中,通过Help -> Eclipse Marketplace,搜索并安装Spring Tools 4。

在IDEA中,完成Spring Boot插件安装后,可以尝试创建一个新的Spring Boot项目以检查安装是否成功。

快速创建第一个SpringBoot项目

首先,打开IDEA,选择File -> New -> Project,然后选择Spring Initializr,点击Next

在弹出的窗口中,选择Maven作为构建工具,填写GroupArtifact信息,选择语言为Java,版本为11,然后点击Next

在框架选择窗口,选择Spring WebSpring Boot DevTools,点击Next,最后点击Finish创建项目。

项目创建完成后,IDEA会自动下载所需的依赖,并完成项目的初始化。此时,项目结构大致如下:

src
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               └── DemoApplication.java
    └── resources
        └── application.properties

DemoApplication.java 是项目的主启动类,application.properties 是项目的配置文件。在DemoApplication.java中,主要代码如下:

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);
    }
}

@SpringBootApplication注解是SpringBoot的核心注解,它组合了@Configuration@EnableAutoConfiguration@ComponentScan三个注解,用来表示SpringBoot应用的主类。

application.properties文件中可以配置应用的各种属性,例如端口号、数据库连接信息等。

要运行项目,只需点击IDEA的运行按钮,或者在终端中运行mvn spring-boot:run命令。

SpringBoot核心概念介绍

自动配置

SpringBoot通过@EnableAutoConfiguration注解来实现自动配置。当SpringBoot在应用中找到这个注解时,它会自动配置应用的各个组件,例如数据库连接、Web服务器、定时任务等。

SpringBoot自动配置的原理是:SpringBoot会查找类路径下的META-INF/spring.factories文件,读取配置项并根据这些配置项创建相应的配置类。这些配置类就是用来实现自动配置功能的。

例如,如果你的项目中引入了Spring Data JPA的依赖,SpringBoot会自动配置一个JPA的EntityManagerFactory和JpaTransactionManager。

启动类

一个SpringBoot应用必须有一个主配置类,该类由@SpringBootApplication注解标记。这个注解是在DemoApplication.java中看到的。

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);
    }
}

@SpringBootApplication注解表示这是一个SpringBoot启动类,它组合了@Configuration@EnableAutoConfiguration@ComponentScan三个注解,用来表示SpringBoot应用的主类。@Configuration表示这是一个配置类,@EnableAutoConfiguration表示开启自动配置,@ComponentScan表示扫描指定包下的组件。

配置文件

SpringBoot使用application.propertiesapplication.yml来配置应用的各种属性。这些配置文件通常位于src/main/resources目录下。

例如,要设置应用运行的端口,可以修改application.properties文件:

server.port=8080

此外,SpringBoot还支持外部配置,例如环境变量、系统属性或命令行参数。

依赖管理和热启动

SpringBoot使用Maven或Gradle来管理项目依赖。在pom.xml文件中,通过<dependency>标签引入需要的依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

spring-boot-starter-web依赖包含了Spring Boot Web应用所需的组件,例如Servlet容器、Spring MVC等。spring-boot-starter-test依赖则包含了测试所需的依赖。

SpringBoot还提供了热启动功能,可以在代码修改后无需重启应用即可看到效果。要开启热启动,只需在pom.xml文件中引入spring-boot-devtools依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
</dependency>

SpringBoot常用注解详解

@SpringBootApplication

@SpringBootApplication是SpringBoot的核心注解,它组合了@Configuration@EnableAutoConfiguration@ComponentScan三个注解,用来表示SpringBoot应用的主类。

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);
    }
}

@RestController注解

@RestController是SpringMVC中的@Controller注解和@ResponseBody注解的组合。@RestController注解的作用是创建一个控制器类,该控制器类会像@Controller那样处理HTTP请求,但返回的视图名称会被直接作为响应体的文本内容。这种方式常用于JSON数据的返回。

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, SpringBoot!";
    }
}

@Autowired注解

@Autowired注解用于自动装配依赖,SpringBoot会根据类型或名称自动查找并注入对应的对象。例如,在HelloController中,可以通过@Autowired注解注入HelloService对象。

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    private final HelloService helloService;

    @Autowired
    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @GetMapping("/hello")
    public String hello() {
        return helloService.getMessage();
    }
}

package com.example.demo;

public class HelloService {
    public String getMessage() {
        return "Hello, SpringBoot!";
    }
}

@ComponentScan注解

@ComponentScan注解用于指定扫描组件的包路径。SpringBoot会自动扫描应用的主类所在包及其子包下的标记了@Component@Service@Repository@Controller等注解的类,并将这些类注册为Spring容器中的bean。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.example.demo")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

SpringBoot数据访问技术

JPA数据访问

SpringBoot支持JPA(Java Persistence API)来实现数据访问。JPA是对JDBC的抽象,提供了更高级的API来操作数据库。JPA的主要优点是提供了标准的ORM(对象关系映射)实现,可以将Java对象映射为数据库表。

要使用JPA,首先需要在项目中引入Spring Data JPA的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
``

然后定义实体类,使用`@Entity`注解表示这是一个持久化的实体类。

```java
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 String email;

    // 省略getter和setter方法
}

接下来定义一个JPA仓库接口,使用@Repository注解表示这是一个持久层的组件。

```java.

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

最后在服务层中使用@Autowired注解注入仓库接口,然后就可以使用仓库接口提供的方法来操作数据库了。

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 addUser(User user) {
        return userRepository.save(user);
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

MyBatis集成

SpringBoot也支持MyBatis来实现数据访问。MyBatis是一个支持自定义SQL、存储过程和高级映射的优秀的持久层框架。要使用MyBatis,首先需要在项目中引入Spring Boot MyBatis的依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
``

然后定义实体类,使用`@Entity`注解表示这是一个持久化的实体类。

```java
package com.example.demo.entity;

public class User {
    private Long id;
    private String name;
    private String email;

    // 省略getter和setter方法
}
``

接下来定义一个MyBatis的映射文件,例如`UserMapper.xml`,配置SQL映射:

```xml
<mapper namespace="com.example.demo.mapper.UserMapper">
    <select id="getUserById" resultType="com.example.demo.entity.User">
        SELECT id, name, email FROM user WHERE id = #{id}
    </select>
</mapper>
``

在MyBatis的映射接口中编写SQL映射方法:

```java
package com.example.demo.mapper;

import com.example.demo.entity.User;

public interface UserMapper {
    User getUserById(Long id);
}

最后在服务层中使用@Autowired注解注入映射接口,然后就可以使用映射接口提供的方法来操作数据库了。

package com.example.demo.service;

import com.example.demo.entity.User;
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(Long id) {
        return userMapper.getUserById(id);
    }
}

SpringBoot与数据库交互案例

下面以一个简单的SpringBoot应用为例,展示如何与数据库进行交互。

  1. 创建数据库表

    创建一个名为user的表,其中包含idnameemail三个字段。

    CREATE TABLE user (
       id BIGINT AUTO_INCREMENT PRIMARY KEY,
       name VARCHAR(255) NOT NULL,
       email VARCHAR(255) NOT NULL
    );
  2. 定义实体类

    在项目中定义一个User实体类,用于映射数据库表中的数据。

    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 String email;
    
       // 省略getter和setter方法
    }
  3. 定义仓库接口

    定义一个UserRepository接口,继承JpaRepository接口,用于与数据库进行交互。

    package com.example.demo.repository;
    
    import com.example.demo.entity.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    }
  4. 定义服务层

    在服务层中定义UserService类,注入UserRepository接口,并实现与数据库交互的方法。

    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 addUser(User user) {
           return userRepository.save(user);
       }
    
       public User getUserById(Long id) {
           return userRepository.findById(id).orElse(null);
       }
    }
  5. 定义控制器

    在控制器层定义UserController类,注入UserService,并实现HTTP请求的处理。

    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.*;
    
    @RestController
    public class UserController {
       @Autowired
       private UserService userService;
    
       @PostMapping("/users")
       public User addUser(@RequestBody User user) {
           return userService.addUser(user);
       }
    
       @GetMapping("/users/{id}")
       public User getUserById(@PathVariable Long id) {
           return userService.getUserById(id);
       }
    }
  6. 启动应用

    在主类DemoApplication.java中启动应用。

    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);
       }
    }

SpringBoot常见功能实现

日志配置

SpringBoot支持多种日志框架,包括Logback、Log4j2、JUL等。默认情况下,SpringBoot使用Logback作为日志框架,并配置了基本的日志级别、输出格式、输出位置等。

要自定义日志配置,可以在application.properties文件中修改相关配置项,或者在src/main/resources目录下添加自定义的logback-spring.xml配置文件。

例如,要修改日志级别,可以在application.properties文件中添加以下配置:

logging.level.root=INFO
logging.level.com.example.demo=WARN

也可以在logback-spring.xml文件中进行更详细的配置:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.example.demo" level="WARN"/>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

任务调度

SpringBoot支持使用@Scheduled注解来实现定时任务。要使用定时任务,首先需要引入spring-boot-starter-task依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-task</artifactId>
</dependency>

然后在任务类中使用@Scheduled注解定义定时任务。

package com.example.demo;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class ScheduledTask {
    @Scheduled(fixedRate = 5000)
    public void task() {
        System.out.println("执行定时任务:" + System.currentTimeMillis());
    }
}

@EnableScheduling注解表示启用定时任务功能,fixedRate属性表示任务执行的固定时间间隔。

异常处理

SpringBoot支持使用@ControllerAdvice@ExceptionHandler注解来实现全局异常处理。@ControllerAdvice注解表示这是一个全局异常处理器,@ExceptionHandler注解表示处理特定类型的异常。

package com.example.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<String> handleException(Exception e) {
        return new ResponseEntity<>("发生异常:" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

在上述代码中,@ControllerAdvice注解表示这是一个全局异常处理器,@ExceptionHandler注解表示处理所有类型的异常。当控制器抛出未捕获的异常时,GlobalExceptionHandler类中的handleException方法会被调用,返回一个包含异常信息的响应体。

静态资源处理

SpringBoot默认支持静态资源的处理,例如HTML、CSS、JavaScript文件等。这些静态资源文件通常放在src/main/resources/static目录下。

例如,可以在src/main/resources/static目录下创建一个index.html文件,放在应用的根路径上。

<!DOCTYPE html>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h1>欢迎来到首页</h1>
</body>
</html>

当访问/路径时,SpringBoot会自动返回index.html文件的内容。此外,SpringBoot还支持使用@Controller注解定义控制器类,处理静态资源请求。

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StaticResourceController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, SpringBoot!";
    }
}

SpringBoot项目打包与部署

打包项目

要打包SpringBoot项目,可以使用Maven或Gradle等构建工具。使用Maven打包时,可以在终端中输入mvn clean package命令,生成一个可执行的jar文件。

mvn clean package

生成的jar文件位于target目录下,文件名为<artifactId>-<version>.jar

要启动这个jar文件,可以使用java -jar命令,并指定-Dspring.profiles.active属性来激活不同的配置文件。

java -jar target/<artifactId>-<version>.jar --spring.profiles.active=production

运行jar包

在命令行中,使用java -jar命令启动jar文件。

java -jar target/<artifactId>-<version>.jar

部署到服务器

部署到服务器的方法有很多种,包括使用Docker容器、Tomcat服务器等。

  1. 使用Docker容器

    首先,需要创建一个Dockerfile文件,定义容器的构建过程。

    FROM openjdk:11-jre-slim
    VOLUME /tmp
    ARG JAR_FILE=target/<artifactId>-<version>.jar
    COPY ${JAR_FILE} app.jar
    ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

    然后,使用docker build命令构建Docker镜像。

    docker build -t <image-name> .

    最后,使用docker run命令启动Docker容器。

    docker run -d -p 8080:8080 <image-name>
  2. 使用Tomcat服务器

    将jar文件解压到Tomcat的webapps目录下,启动Tomcat服务器,应用会自动部署到Tomcat服务器上。

    cp target/<artifactId>-<version>.jar /path/to/tomcat/webapps/<artifactId>.war
    cd /path/to/tomcat/bin
    ./startup.sh

通过以上步骤,可以将SpringBoot应用部署到生产环境中,并确保应用能够正常运行。

點擊查看更多內(nèi)容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優(yōu)惠券免費領(lǐng)

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消