主頁 > 後端開發 > 2021 最新版 Spring Boot 速記教程

2021 最新版 Spring Boot 速記教程

2021-01-26 06:19:29 後端開發

Demo 腳手架專案地址:
Table of Contents
generated with DocToc

SpringBoot 速記

一、引入依賴

二、配置 Swagger 引數

一、引入依賴

二、配置郵箱的引數

三、寫模板和發送內容

一、參考 Redis 依賴

二、引數配置

三、代碼使用

一、添加 mybatis 和 druid 依賴

二、配置資料庫和連接池引數

三、其他 mybatis 配置

@ExceptionHandler 錯誤處理

@ModelAttribute 視圖屬性

常規配置

HTTPS 配置

構建專案

SpringBoot 基礎配置

Spring Boot Starters

@SpringBootApplication

Web 容器配置

@ConfigurationProperties

Profile

@ControllerAdvice 用來處理全域資料

CORS 支持,跨域資源共享

注冊 MVC 攔截器

開啟 AOP 切面控制

整合 Mybatis 和 Druid

整合 Redis

發送 HTML 樣式的郵件

整合 Swagger (API 檔案)

總結

參考資料
構建專案
相比于使用 IDEA 的模板創建專案,我更推薦的是在 Spring 官網上選擇引數一步生成專案,
start.spring.io/

我們只需要做的事情,就是修改組織名和專案名,點擊 Generate the project,下載到本地,然后使用 IDEA 打開
這個時候,不需要任何配置,點擊 Application 類的 run 方法就能直接啟動專案,
SpringBoot 基礎配置
Spring Boot Starters
參考自參考資料 1 描述:

starter的理念:starter 會把所有用到的依賴都給包含進來,避免了開發者自己去引入依賴所帶來的麻煩,需要注意的是不同的 starter 是為了解決不同的依賴,所以它們內部的實作可能會有很大的差異,例如 jpa 的 starter 和 Redis 的 starter 可能實作就不一樣,這是因為 starter 的本質在于 synthesize,這是一層在邏輯層面的抽象,也許這種理念有點類似于 Docker,因為它們都是在做一個“包裝”的操作,如果你知道 Docker 是為了解決什么問題的,也許你可以用 Docker 和 starter 做一個類比,

我們知道在 SpringBoot 中很重要的一個概念就是,「約定優于配置」,通過特定方式的配置,可以減少很多步驟來實作想要的功能,
例如如果我們想要使用快取 Redis
在之前的可能需要通過以下幾個步驟:

1.在 pom 檔案引入特定版本的 redis

2.在 .properties 檔案中配置引數

3.根據引數,新建一個又一個 jedis 連接

4.定義一個工具類,手動創建連接池來管理

經歷了上面的步驟,我們才能正式使用 Redis
但在 Spring Boot 中,一切因為 Starter 變得簡單

1.在 pom 檔案中引入 spring-boot-starter-data-redis

2.在.properties 檔案中配置引數

通過上面兩個步驟,配置自動生效,具體生效的 bean 是 RedisAutoConfiguration,自動配置類的名字都有一個特點,叫做 xxxAutoConfiguration,
可以來簡單看下這個類:
可以來簡單看下這個類:

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

 @Bean
 @ConditionalOnMissingBean(name = "redisTemplate")
 public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
   throws UnknownHostException {
  RedisTemplate<Object, Object> template = new RedisTemplate<>();
  template.setConnectionFactory(redisConnectionFactory);
  return template;
 }

 @Bean
 @ConditionalOnMissingBean
 public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
   throws UnknownHostException {
  StringRedisTemplate template = new StringRedisTemplate();
  template.setConnectionFactory(redisConnectionFactory);
  return template;
 }

}

@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {...}

可以看到,Redis 自動配置類,讀取了以 spring.redis 為前綴的配置,然后加載 redisTemplate 到容器中,然后我們在應用中就能使用 RedisTemplate 來對快取進行操作~(還有很多細節沒有細說,例如 @ConditionalOnMissingBean 先留個坑(●′?`●)?)

@Autowired
private RedisTemplate redisTemplate;

ValueOperations ops2 = redisTemplate.opsForValue();
Book book = (Book) ops2.get("b1");

@SpringBootApplication
該注解是加載專案的啟動類上的,而且它是一個組合注解:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {...}

下面是這三個核心注解的解釋:

注解名 解釋
@SpringBootConfiguration 表明這是一個配置類,開發者可以在這個類中配置 Bean
@EnableAutoConfiguration 表示開啟自動化配置
@ComponentScan 完成包掃描,默認掃描的類位于當前類所在包的下面
通過該注解,我們執行 mian 方法:

SpringApplication.run(SpringBootLearnApplication.class, args);
就可以啟動一個 SpringApplicaiton 應用了,

Web 容器配置
常規配置
配置名 解釋
server.port=8081 配置了容器的埠號,默認是 8080
server.error.path=/error 配置了專案出錯時跳轉的頁面
server.servlet.session.timeout=30m session 失效時間,m 表示分鐘,如果不寫單位,默認是秒 s
server.servlet.context-path=/ 專案名稱,不配置時默認為/,配置后,訪問時需加上前綴
server.tomcat.uri-encoding=utf-8 Tomcat 請求編碼格式
server.tomcat.max-threads=500 Tomcat 最大執行緒數
server.tomcat.basedir=/home/tmp Tomcat 運行日志和臨時檔案的目錄,如不配置,默認使用系統的臨時目錄
HTTPS 配置
配置名 解釋
server.ssl.key-store=xxx 秘鑰檔案名
server.ssl.key-alias=xxx 秘鑰別名
server.ssl.key-store-password=123456 秘鑰密碼
想要詳細了解如何配置 HTTPS,可以參考這篇文章 Spring Boot 使用SSL-HTTPS

@ConfigurationProperties
這個注解可以放在類上或者 @Bean 注解所在方法上,這樣 SpringBoot 就能夠從組態檔中,讀取特定前綴的配置,將屬性值注入到對應的屬性,

使用例子:

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidConfigBean {

    private Integer initialSize;

    private Integer minIdle;

    private Integer maxActive;
    
    private List<String> customs;
    
    ...
}
application.properties
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.customs=test1,test2,test3

其中,如果物件是串列結構,可以在組態檔中使用 , 逗號進行分割,然后注入到相應的屬性中,

Profile
使用該屬性,可以快速切換組態檔,在 SpringBoot 默認約定中,不同環境下組態檔名稱規則為 application-{profile}.propertie,profile 占位符表示當前環境的名稱,

1、配置 application.properties

spring.profiles.active=dev
2、在代碼中配置 在啟動類的 main 方法上添加 setAdditionalProfiles("{profile}");


SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringBootLearnApplication.class);
builder.application().setAdditionalProfiles("prod");
builder.run(args);

3、啟動引數配置

java -jar demo.jar --spring.active.profile=dev
@ControllerAdvice 用來處理全域資料
@ControllerAdvice 是 @Controller 的增強版,主要用來處理全域資料,一般搭配 @ExceptionHandler 、@ModelAttribute 以及 @InitBinder 使用,

@ExceptionHandler 錯誤處理

/**
 * 加強版控制器,攔截自定義的例外處理
 *
 */
@ControllerAdvice
public class CustomExceptionHandler {
    
    // 指定全域攔截的例外型別,統一處理
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("上傳檔案大小超出限制");
        out.flush();
        out.close();
    }
}

@ModelAttribute 視圖屬性

@ControllerAdvice
public class CustomModelAttribute {
    
    // 
    @ModelAttribute(value = "https://www.cnblogs.com/rutaha/p/info")
    public Map<String, String> userInfo() throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("test", "testInfo");
        return map;
    }
}


@GetMapping("/hello")
public String hello(Model model) {
    Map<String, Object> map = model.asMap();
    Map<String, String> infoMap = (Map<String, String>) map.get("info");
    return infoMap.get("test");
}

key : @ModelAttribute 注解中的 value 屬性
使用場景:任何請求 controller 類,通過方法引數中的 Model 都可以獲取 value 對應的屬性
關注公眾號有故事的程式員,回子書 獲取最新學習資料 ,
CORS 支持,跨域資源共享
CORS(Cross-Origin Resource Sharing),跨域資源共享技術,目的是為了解決前端的跨域請求,


參考:當一個資源從與該資源本身所在服務器不同的域或埠請求一個資源時,資源會發起一個跨域HTTP請求

詳細可以參考這篇文章-springboot系列文章之實作跨域請求(CORS),這里只是記錄一下如何使用:

例如在我的前后端分離 demo 中,如果沒有通過 Nginx 轉發,那么將會提示如下資訊:


Access to fetch at ‘http://localhost:8888/login‘ from origin ‘http://localhost:3000‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’

為了解決這個問題,在前端不修改的情況下,需要后端加上如下兩行代碼:

// 第一行,支持的域

@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "https://www.cnblogs.com/login", method = RequestMethod.GET)
@ResponseBody
public String login(HttpServletResponse response) {
    // 第二行,回應體添加頭資訊(這一行是解決上面的提示)
    response.setHeader("Access-Control-Allow-Credentials", "true");
    return HttpRequestUtils.login();
}

注冊 MVC 攔截器
在 MVC 模塊中,也提供了類似 AOP 切面管理的擴展,能夠擁有更加精細的攔截處理能力,

核心在于該介面:HandlerInterceptor,使用方式如下:


/**
 * 自定義 MVC 攔截器
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在 controller 方法之前呼叫
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在 controller 方法之后呼叫
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在 postHandle 方法之后呼叫
    }
}

注冊代碼:

/**
 * 全域控制的 mvc 配置
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                // 表示攔截的 URL
                .addPathPatterns("/**")
                // 表示需要排除的路徑
                .excludePathPatterns("/hello");
    }
}

攔截器執行順序:preHandle -> controller -> postHandle -> afterCompletion,同時需要注意的是,只有 preHandle 方法回傳 true,后面的方法才會繼續執行,

開啟 AOP 切面控制
切面注入是老生常談的技術,之前學習 Spring 時也有了解,可以參考我之前寫過的文章參考一下:

Spring自定義注解實作AOP

Spring 原始碼學習(八) AOP 使用和實作原理

在 SpringBoot 中,使用起來更加簡便,只需要加入該依賴,使用方法與上面一樣,

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

整合 Mybatis 和 Druid
SpringBoot 整合資料庫操作,目前主流使用的是 Druid 連接池和 Mybatis 持久層,同樣的,starter 提供了簡潔的整合方案

專案結構如下:

一、添加 mybatis 和 druid 依賴

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

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.18</version>
</dependency>

二、配置資料庫和連接池引數

# 資料庫配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=12345678

# druid 配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.max-open-prepared-statements=20
spring.datasource.druid.validation-query=SELECT 1
spring.datasource.druid.validation-query-timeout=30000
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=false
#spring.datasource.druid.time-between-eviction-runs-millis=
#spring.datasource.druid.min-evictable-idle-time-millis=
#spring.datasource.druid.max-evictable-idle-time-millis=10000

# Druid stat filter config
spring.datasource.druid.filters=stat,wall
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
# session 監控
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=10
spring.datasource.druid.web-stat-filter.principal-session-name=admin
spring.datasource.druid.web-stat-filter.principal-cookie-name=admin
spring.datasource.druid.web-stat-filter.profile-enable=true
# stat 監控
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=1000
spring.datasource.druid.filter.stat.merge-sql=true
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.delete-allow=true
spring.datasource.druid.filter.wall.config.drop-table-allow=false

# Druid manage page config
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
#spring.datasource.druid.stat-view-servlet.allow=
#spring.datasource.druid.stat-view-servlet.deny=
spring.datasource.druid.aop-patterns=cn.sevenyuan.demo.*

三、其他 mybatis 配置
本地工程,將 xml 檔案放入 resources 資源檔案夾下,所以需要加入以下配置,讓應用進行識別:

<build>
   <resources>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*</include>
           </includes>
       </resource>
   </resources>
   ...
</build>

通過上面的配置,我本地開啟了三個頁面的監控:SQL 、 URL 和 Sprint 監控,如下圖:

通過上面的配置,SpringBoot 很方便的就整合了 Druid 和 mybatis,同時根據在 properties 檔案中配置的引數,開啟了 Druid 的監控,

但我根據上面的配置,始終開啟不了 session 監控,所以如果需要配置 session 監控或者調整引數具體配置,可以查看官方網站

整合 Redis
我用過 Redis 和 NoSQL,但最熟悉和常用的,還是 Redis ,所以這里記錄一下如何整合

一、參考 Redis 依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>lettuce-core</artifactId>
            <groupId>io.lettuce</groupId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

二、引數配置

# redis 配置
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0

三、代碼使用

@Autowired
private RedisTemplate redisTemplate;

@Autowired
private StringRedisTemplate stringRedisTemplate;

@GetMapping("/testRedis")
public Book getForRedis() {
    ValueOperations<String, String> ops1 = stringRedisTemplate.opsForValue();
    ops1.set("name", "Go 語言實戰");
    String name = ops1.get("name");
    System.out.println(name);
    ValueOperations ops2 = redisTemplate.opsForValue();
    Book book = (Book) ops2.get("b1");
    if (book == null) {
        book = new Book("Go 語言實戰", 2, "none name", BigDecimal.ONE);
        ops2.set("b1", book);
    }
    return book;
}

這里只是簡單記錄參考和使用方式,更多功能可以看這里:

發送 HTML 樣式的郵件
之前也使用過,所以可以參考這篇文章:

一、引入依賴

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

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

二、配置郵箱的引數

# mail
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxxxxxxx
spring.mail.password=xxxxxxxx
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

如果使用的是 QQ 郵箱,需要在郵箱的設定中獲取授權碼,填入上面的 password 中

三、寫模板和發送內容

MailServiceImpl.java
@Autowired
private JavaMailSender javaMailSender;

@Override
public void sendHtmlMail(String from, String to, String subject, String content) {
    try {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        javaMailSender.send(message);
    } catch (MessagingException e) {
        System.out.println("發送郵件失敗");
        log.error("發送郵件失敗", e);
    }
}
mailtemplate.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>郵件</title>
</head>
<body>
<div th:text="${subject}"></div>
<div>書籍清單
    <table border="1">
        <tr>
            <td>圖書編號</td>
            <td>圖書名稱</td>
            <td>圖書作者</td>
        </tr>
        <tr th:each="book:${books}">
            <td th:text="${book.id}"></td>
            <td th:text="${book.name}"></td>
            <td th:text="${book.author}"></td>
        </tr>
    </table>
</div>
</body>
</html>
test.java
@Autowired
private MailService mailService;

@Autowired
private TemplateEngine templateEngine;
    
@Test
public void sendThymeleafMail() {
    Context context = new Context();
    context.setVariable("subject", "圖書清冊");
    List<Book> books = Lists.newArrayList();
    books.add(new Book("Go 語言基礎", 1, "nonename", BigDecimal.TEN));
    books.add(new Book("Go 語言實戰", 2, "nonename", BigDecimal.TEN));
    books.add(new Book("Go 語言進階", 3, "nonename", BigDecimal.TEN));
    context.setVariable("books", books);
    String mail = templateEngine.process("mailtemplate.html", context);
    mailService.sendHtmlMail("[email protected]", "[email protected]", "圖書清冊", mail);
}

通過上面簡單步驟,就能夠在代碼中發送郵件,例如我們每周要寫周報,統計系統運行狀態,可以設定定時任務,統計資料,然后自動化發送郵件,

整合 Swagger (API 檔案)
一、引入依賴

<!-- swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

二、配置 Swagger 引數

SwaggerConfig.java
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {

    @Bean
    Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.sevenyuan.demo.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(
                        new ApiInfoBuilder()
                                .description("Spring Boot learn project")
                                .contact(new Contact("JingQ", "https://github.com/vip-augus", "[email protected]"))
                                .version("v1.0")
                                .title("API 測驗檔案")
                                .license("Apache2.0")
                                .licenseUrl("http://www.apache.org/licenese/LICENSE-2.0")
                                .build());

    }
}

設定頁面 UI

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60)
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

通過這樣就能夠識別 @ApiOperation 等介面標志,在網頁查看 API 檔案,參考檔案:Spring Boot實戰:集成Swagger2

總結
這邊總結的整合經驗,只是很基礎的配置,在學習的初期,秉著先跑起來,然后不斷完善和精進學習,

而且單一整合很容易,但多個依賴會出現想不到的錯誤,所以在解決環境問題時遇到很多坑,想要使用基礎的腳手架,可以嘗試跑我上傳的專案,

資料庫腳本在 resources 目錄的 test.sql 檔案中

本文來源:http://r6d.cn/X6FP

總結了一些2020年的面試題,這份面試題的包含的模塊分為19個模塊,分別是: Java基礎、容器、多執行緒、反射、物件拷貝、JavaWeb例外、網路、設計模式、Spring/SpringMVC、SpringBoot/SpringCloud、Hibernate、MyBatis、RabbitMQ、Kafka、Zookeeper、MySQL、Redis、JVM,
獲取以下資料,關注公眾號:【有故事的程式員】,
記得點個關注+評論哦~

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252445.html

標籤:Java

上一篇:Java排序演算法(四)希爾排序2

下一篇:Spring-boot SSM金融股票市場實踐 詳解

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more