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

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定

Springboot框架學(xué)習(xí):從入門到實(shí)踐指南

標(biāo)簽:
SpringBoot

本文将带你全面了解Spring Boot框架学习,包括其简介、优势、核心概念以及如何搭建开发环境。文章还将详细介绍如何创建并运行第一个Spring Boot应用,并深入讲解常用注解与配置。此外,还将涵盖Spring Boot集成技术、项目部署等相关内容,帮助你快速上手和应用Spring Boot框架。

Spring Boot简介

什么是Spring Boot

Spring Boot是由Pivotal团队开发的一款基于Spring框架的简化开发配置的工具。它旨在简化Spring应用的初始搭建以及配置过程,使得开发者可以更快地创建独立的、生产级别的应用。Spring Boot通过提供默认配置来减少代码量,使开发者能够迅速上手并专注于业务逻辑的实现。

Spring Boot的优势

  1. 自动配置:Spring Boot能够自动配置各种框架和库,如数据库连接、数据源、日志等,极大地简化了开发流程。
  2. 独立运行:Spring Boot应用可以打包为独立的可执行文件,包含所有依赖库,可以在任何环境中运行,简化了部署流程。
  3. 无代码生成:Spring Boot不需要繁琐的XML配置文件,提倡使用注解,减少了代码量,提高了开发效率。
  4. 嵌入式服务器:Spring Boot支持内嵌Tomcat、Jetty或Undertow等Web服务器,可以直接启动应用,无需额外配置外部服务器。
  5. 健康检查与监控:Spring Boot自带了Actuator模块,提供了一系列端点来监控应用的健康状态,并提供了详细的运行时信息。
  6. 开发脚手架:Spring Boot提供了各种脚手架,如Spring Initializr,通过简单的配置即可快速搭建项目骨架。

Spring Boot的核心概念

  1. 自动配置:Spring Boot根据应用的类路径中的jar包依赖自动配置应用。例如,如果应用中存在spring-boot-starter-data-jpa依赖,Spring Boot会自动配置JPA相关的配置。
  2. 起步依赖:Spring Boot使用“起步依赖”来简化Maven或Gradle配置。例如,spring-boot-starter-web自动包含了Spring MVC和Tomcat。
  3. 命令行接口:Spring Boot有一个spring-boot-cli命令行接口,可以用来快速创建新的应用,简化运行脚本和执行操作。

示例代码

// 使用@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);
    }
}
Spring Boot环境搭建

安装Java开发环境

  1. 下载Java JDK:前往Oracle官方网站或OpenJDK下载最新版本的Java JDK。
  2. 安装Java JDK:解压下载的文件到指定目录,并设置环境变量。
  3. 验证安装
    • 打开命令行工具,输入java -version,查看Java版本信息。
    • 输入javac -version,查看Java编译器版本信息。

下载并配置Spring Boot

  1. 下载Spring Boot Starter:访问Spring Boot官方文档页面,下载所需的起步依赖包。
  2. 配置环境变量:设置环境变量SPRING_HOME指向Spring Boot安装目录,并将%SPRING_HOME%\bin添加到系统环境变量PATH中。
  3. 验证安装:在命令行工具中输入spring命令,查看是否正确安装。

使用IDEA搭建Spring Boot项目

  1. 创建新项目
    • 打开IntelliJ IDEA,选择“File” -> “New” -> “Project”。
    • 在弹出的窗口中选择“Spring Initializr”,点击“Next”。
  2. 配置项目信息
    • 选择语言(Java),版本(推荐版本)。
    • 输入项目名称(如DemoSpringBoot),选择项目位置。
    • 选择Spring Boot版本(如2.4.0)。
  3. 选择启动依赖
    • 选择WebJPA等依赖。
    • 点击“Next”将项目创建到指定位置。
  4. 导入项目
    • 项目创建完成后,选择File -> Open -> 选择项目目录,打开项目。
第一个Spring Boot应用

创建Spring Boot项目

  1. 创建项目骨架
    • 使用Spring Initializr创建一个新的Spring Boot项目。
  2. 项目结构
    • 主类:DemoApplication.java
    • 控制器:HelloController.java
    • 配置文件:application.properties

实现简单的Hello World应用

  1. 主类
    • 创建一个主类DemoApplication.java,使用@SpringBootApplication注解。
      . 在主类中定义main方法,启动Spring Boot应用。
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);
    }
}
  1. 控制器
    • 创建一个控制器类HelloController.java,使用@RestController注解。
    • 在控制器中定义一个处理HTTP请求的方法,返回“Hello World”。
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 sayHello() {
        return "Hello World!";
    }
}

运行并测试应用

  1. 运行应用
    • 在IDEA中右键点击DemoApplication.java,选择“Run”运行应用。
    • 应用启动后,控制台输出Started DemoApplication in X seconds (JVM running for Y)
  2. 测试应用
    • 打开浏览器,访问http://localhost:8080/hello
    • 页面显示“Hello World!”。
Spring Boot常用注解与配置

@SpringBootApplication注解详解

@SpringBootApplication是一个组合注解,包含以下三个注解:

  • @Configuration:表示当前类是配置类,可以包含其他配置信息。
  • @EnableAutoConfiguration:开启自动配置功能。
  • @ComponentScan:扫描Spring Boot应用中的其他组件。
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);
    }
}

配置文件的使用(application.properties/application.yml)

  1. application.properties

    • 使用=分隔键值对。
    • 例如:server.port=8080设置应用监听端口为8080。
  2. application.yml
    • 使用:分隔键值对。
    • 例如:
      server:
      port: 8080

自动配置机制

Spring Boot通过spring.factories文件启动自动配置过程,这个文件位于各个依赖的META-INF目录下。Spring Boot会扫描这些文件,并调用其中定义的配置类来完成自动配置。

  1. 自动配置类
    • 例如,org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration用于配置Servlet容器。
  2. 优先级
    • 自动配置优先级可以通过@Conditional注解来控制,例如@ConditionalOnClass@ConditionalOnMissingBean等。

示例代码

# application.properties
server.port=8080
spring.application.name=demo-app
# application.yml
server:
  port: 8080
spring:
  application:
   name: demo-app
Spring Boot集成技术

集成JPA实现数据库操作

  1. 添加依赖
    • pom.xmlbuild.gradle中添加spring-boot-starter-data-jpa依赖。
  2. 配置数据库
    • application.propertiesapplication.yml中配置数据库连接信息。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
  1. 创建实体类
    • 使用@Entity注解创建实体类。
    • 使用@Id注解标识主键。
    • 使用@GeneratedValue注解自动生成主键。
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;

    // getters and setters
}
  1. 创建Repository接口
    • 使用@Repository注解创建Repository接口。
    • 使用@Repository注解的接口会自动被Spring Boot识别并实现。
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> {
}
  1. 创建服务类
    • 使用@Service注解创建服务类。
    • 在服务类中注入Repository接口,并实现业务逻辑。
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 saveUser(User user) {
        return userRepository.save(user);
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}
  1. 创建控制器
    • 使用@RestController注解创建控制器。
    • 在控制器中调用服务类的方法。
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
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public User saveUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

集成Thymeleaf实现前端页面渲染

  1. 添加依赖

    • pom.xmlbuild.gradle中添加spring-boot-starter-thymeleaf依赖。
  2. 创建HTML页面
    • src/main/resources/templates目录下创建HTML页面文件。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="${greeting}">Hello, World!</h1>
</body>
</html>
  1. 创建控制器
    • 在控制器中返回带有模型数据的视图名称。
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("greeting", "Hello, Thymeleaf!");
        return "thymeleaf";
    }
}

集成Spring Security实现安全认证

  1. 添加依赖

    • pom.xmlbuild.gradle中添加spring-boot-starter-security依赖。
  2. 配置安全策略
    • application.propertiesapplication.yml中配置安全相关的属性。
    • 创建WebSecurityConfig类,配置安全策略。
# application.properties
spring.security.user.name=admin
spring.security.user.password=admin
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
Spring Boot项目部署

打包Spring Boot应用

  1. 打包命令

    • 在IDE中右键点击DemoApplication.java,选择“Maven” -> “Package”打包项目。
    • 或者在命令行中输入mvn clean package打包项目。
  2. 生成的文件
    • 打包完成后,会在target目录下生成demo-0.0.1-SNAPSHOT.jar文件。

部署到Tomcat服务器

  1. 下载并安装Tomcat

    • 前往Apache官方网站下载最新版本的Tomcat。
    • 解压Tomcat压缩包,设置环境变量CATALINA_HOME
  2. 部署应用
    • demo-0.0.1-SNAPSHOT.jar文件复制到Tomcat的webapps目录下。
    • 启动Tomcat服务器。

部署到云服务器

  1. 上传文件

    • 使用FTP工具或SCP命令将demo-0.0.1-SNAPSHOT.jar文件上传到云服务器。
  2. 启动应用

    • 使用命令行工具启动应用:
      java -jar demo-0.0.1-SNAPSHOT.jar
  3. 监控应用
    • 使用psjps命令查看应用进程。
    • 使用curl命令测试应用是否正常运行:
      curl http://localhost:8080/hello

示例代码

# 打包命令
mvn clean package

# 启动Tomcat服务器
cd /path/to/tomcat
bin/startup.sh

# 上传文件到云服务器命令
scp demo-0.0.1-SNAPSHOT.jar user@server:/path/to/deploy
ssh user@server
cd /path/to/deploy
java -jar demo-0.0.1-SNAPSHOT.jar
點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評論

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

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

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

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

立即參與 放棄機(jī)會(huì)
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

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

舉報(bào)

0/150
提交
取消