主頁 > 後端開發 > spring中的這些開發技巧真的太diao了

spring中的這些開發技巧真的太diao了

2021-04-29 11:35:07 後端開發

前言

最近越來越多的讀者認可我的文章,還是件挺讓人高興的事情,有些讀者私信我說希望后面多分享spring方面的文章,這樣能夠在實際作業中派上用場,正好我對spring原始碼有過一定的研究,并結合我這幾年實際的作業經驗,把spring中我認為不錯的知識點總結一下,希望對您有所幫助,

一 如何獲取spring容器物件

1.實作BeanFactoryAware介面

@Service
public class PersonService implements BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void add() {
        Person person = (Person) beanFactory.getBean("person");
    }
}

實作BeanFactoryAware介面,然后重寫setBeanFactory方法,就能從該方法中獲取到spring容器物件,

2.實作ApplicationContextAware介面

@Service
public class PersonService2 implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void add() {
        Person person = (Person) applicationContext.getBean("person");
    }

}

實作ApplicationContextAware介面,然后重寫setApplicationContext方法,也能從該方法中獲取到spring容器物件,

3.實作ApplicationListener介面

@Service
public class PersonService3 implements ApplicationListener<ContextRefreshedEvent> {
    private ApplicationContext applicationContext;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        applicationContext = event.getApplicationContext();
    }

    public void add() {
        Person person = (Person) applicationContext.getBean("person");
    }

}

實作ApplicationListener介面,需要注意的是該介面接收的泛型是ContextRefreshedEvent類,然后重寫onApplicationEvent方法,也能從該方法中獲取到spring容器物件,

此外,不得不提一下Aware介面,它其實是一個空介面,里面不包含任何方法,

它表示已感知的意思,通過這類介面可以獲取指定物件,比如:

  • 通過BeanFactoryAware獲取BeanFactory
  • 通過ApplicationContextAware獲取ApplicationContext
  • 通過BeanNameAware獲取BeanName等
    Aware介面是很常用的功能,目前包含如下功能:

在這里插入圖片描述

二 如何初始化bean

spring中支持3種初始化bean的方法:

  • xml中指定init-method方法
  • 使用@PostConstruct注解
  • 實作InitializingBean介面

第一種方法太古老了,現在用的人不多,具體用法就不介紹了,

1.使用@PostConstruct注解

@Service
public class AService {

    @PostConstruct
    public void init() {
        System.out.println("===初始化===");
    }
}

在需要初始化的方法上增加@PostConstruct注解,這樣就有初始化的能力,

2.實作InitializingBean介面

@Service
public class BService implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("===初始化===");
    }
}

實作InitializingBean介面,重寫afterPropertiesSet方法,該方法中可以完成初始化功能,

這里順便拋出一個有趣的問題:init-methodPostConstructInitializingBean 的執行順序是什么樣的?

決定他們呼叫順序的關鍵代碼在AbstractAutowireCapableBeanFactory類的initializeBean方法中,
在這里插入圖片描述

這段代碼中會先呼叫BeanPostProcessorpostProcessBeforeInitialization方法,而PostConstruct是通過InitDestroyAnnotationBeanPostProcessor實作的,它就是一個BeanPostProcessor,所以PostConstruct先執行,

invokeInitMethods方法中的代碼:

在這里插入圖片描述

決定了先呼叫InitializingBean,再呼叫init-method

所以得出結論,他們的呼叫順序是:

在這里插入圖片描述

三 自定義自己的Scope

我們都知道spring默認支持的Scope只有兩種:

  • singleton 單例,每次從spring容器中獲取到的bean都是同一個物件,
  • prototype 多例,每次從spring容器中獲取到的bean都是不同的物件,

spring web又對Scope進行了擴展,增加了:

  • RequestScope 同一次請求從spring容器中獲取到的bean都是同一個物件,
  • SessionScope 同一個會話從spring容器中獲取到的bean都是同一個物件,

即便如此,有些場景還是無法滿足我們的要求,

比如,我們想在同一個執行緒中從spring容器獲取到的bean都是同一個物件,該怎么辦?

這就需要自定義Scope了,

第一步實作Scope介面:

public class ThreadLocalScope implements Scope {

    private static final ThreadLocal THREAD_LOCAL_SCOPE = new ThreadLocal();

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object value = THREAD_LOCAL_SCOPE.get();
        if (value != null) {
            return value;
        }

        Object object = objectFactory.getObject();
        THREAD_LOCAL_SCOPE.set(object);
        return object;
    }

    @Override
    public Object remove(String name) {
        THREAD_LOCAL_SCOPE.remove();
        return null;
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}

第二步將新定義的Scope注入到spring容器中:

@Component
public class ThreadLocalBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.registerScope("threadLocalScope", new ThreadLocalScope());
    }
}

第三步使用新定義的Scope:

@Scope("threadLocalScope")
@Service
public class CService {

    public void add() {
    }
}

四 別說FactoryBean沒用

說起FactoryBean就不得不提BeanFactory,因為面試官老喜歡問它們的區別,

  • BeanFactory:spring容器的頂級介面,管理bean的工廠,
  • FactoryBean:并非普通的工廠bean,它隱藏了實體化一些復雜Bean的細節,給上層應用帶來了便利,

如果你看過spring原始碼,會發現它有70多個地方在用FactoryBean介面,

在這里插入圖片描述

上面這張圖足以說明該介面的重要性,請勿忽略它好嗎?

特別提一句:mybatis的SqlSessionFactory物件就是通過SqlSessionFactoryBean類創建的,

我們一起定義自己的FactoryBean:

@Component
public class MyFactoryBean implements FactoryBean {

    @Override
    public Object getObject() throws Exception {
        String data1 = buildData1();
        String data2 = buildData2();
        return buildData3(data1, data2);
    }

    private String buildData1() {
        return "data1";
    }

    private String buildData2() {
        return "data2";
    }

    private String buildData3(String data1, String data2) {
        return data1 + data2;
    }


    @Override
    public Class<?> getObjectType() {
        return null;
    }
}

獲取FactoryBean實體物件:

@Service
public class MyFactoryBeanService implements BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void test() {
        Object myFactoryBean = beanFactory.getBean("myFactoryBean");
        System.out.println(myFactoryBean);
        Object myFactoryBean1 = beanFactory.getBean("&myFactoryBean");
        System.out.println(myFactoryBean1);
    }
}

getBean("myFactoryBean");獲取的是MyFactoryBeanService類中getObject方法回傳的物件,

getBean("&myFactoryBean");獲取的才是MyFactoryBean物件,

五 輕松自定義型別轉換

spring目前支持3中型別轉換器:

  • Converter<S,T>:將 S 型別物件轉為 T 型別物件
  • ConverterFactory<S, R>:將 S 型別物件轉為 R 型別及子類物件
  • GenericConverter:它支持多個source和目標型別的轉化,同時還提供了source和目標型別的背景關系,這個背景關系能讓你實作基于屬性上的注解或資訊來進行型別轉換,

這3種型別轉換器使用的場景不一樣,我們以Converter<S,T>為例,假如:介面中接收引數的物體物件中,有個欄位的型別是Date,但是實際傳參的是字串型別:2021-01-03 10:20:15,要如何處理呢?

第一步,定義一個物體User:

@Data
public class User {

    private Long id;
    private String name;
    private Date registerDate;
}

第二步,實作Converter介面:

public class DateConverter implements Converter<String, Date> {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date convert(String source) {
        if (source != null && !"".equals(source)) {
            try {
                simpleDateFormat.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

第三步,將新定義的型別轉換器注入到spring容器中:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }
}

第四步,呼叫介面

@RequestMapping("/user")
@RestController
public class UserController {

    @RequestMapping("/save")
    public String save(@RequestBody User user) {
        return "success";
    }
}

請求介面時User物件中registerDate欄位會被自動轉換成Date型別,

六 spring mvc攔截器,用過的都說好

spring mvc攔截器根spring攔截器相比,它里面能夠獲取HttpServletRequestHttpServletResponse 等web物件實體,

spring mvc攔截器的頂層介面是:HandlerInterceptor,包含三個方法:

  • preHandle 目標方法執行前執行
  • postHandle 目標方法執行后執行
  • afterCompletion 請求完成時執行

為了方便我們一般情況會用HandlerInterceptor介面的實作類HandlerInterceptorAdapter類,

假如有權限認證、日志、統計的場景,可以使用該攔截器,

第一步,繼承HandlerInterceptorAdapter類定義攔截器:

public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUrl = request.getRequestURI();
        if (checkAuth(requestUrl)) {
            return true;
        }

        return false;
    }

    private boolean checkAuth(String requestUrl) {
        System.out.println("===權限校驗===");
        return true;
    }
}

第二步,將該攔截器注冊到spring容器:

@Configuration
public class WebAuthConfig extends WebMvcConfigurerAdapter {
 
    @Bean
    public AuthInterceptor getAuthInterceptor() {
        return new AuthInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor());
    }
}

第三步,在請求介面時spring mvc通過該攔截器,能夠自動攔截該介面,并且校驗權限,

該攔截器其實相對來說,比較簡單,可以在DispatcherServlet類的doDispatch方法中看到呼叫程序:

在這里插入圖片描述

順便說一句,這里只講了spring mvc的攔截器,并沒有講spring的攔截器,是因為我有點小私心,后面就會知道,

七 Enable開關真香

不知道你有沒有用過Enable開頭的注解,比如:EnableAsyncEnableCachingEnableAspectJAutoProxy等,這類注解就像開關一樣,只要在@Configuration定義的配置類上加上這類注解,就能開啟相關的功能,

是不是很酷?

讓我們一起實作一個自己的開關:

第一步,定義一個LogFilter:

public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("記錄請求日志");
        chain.doFilter(request, response);
        System.out.println("記錄回應日志");
    }

    @Override
    public void destroy() {
        
    }
}

第二步,注冊LogFilter:

@ConditionalOnWebApplication
public class LogFilterWebConfig {

    @Bean
    public LogFilter timeFilter() {
        return new LogFilter();
    }
}

注意,這里用了@ConditionalOnWebApplication注解,沒有直接使用@Configuration注解,

第三步,定義開關@EnableLog注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(LogFilterWebConfig.class)
public @interface EnableLog {

}

第四步,只需在springboot啟動類加上@EnableLog注解即可開啟LogFilter記錄請求和回應日志的功能,

八 RestTemplate攔截器的春天

我們使用RestTemplate呼叫遠程介面時,有時需要在header中傳遞資訊,比如:traceId,source等,便于在查詢日志時能夠串聯一次完整的請求鏈路,快速定位問題,

這種業務場景就能通過ClientHttpRequestInterceptor介面實作,具體做法如下:

第一步,實作ClientHttpRequestInterceptor介面:

public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set("traceId", MdcUtil.get());
        return execution.execute(request, body);
    }
}

第二步,定義配置類:

@Configuration
public class RestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));
        return restTemplate;
    }

    @Bean
    public RestTemplateInterceptor restTemplateInterceptor() {
        return new RestTemplateInterceptor();
    }
}

其中MdcUtil其實是利用MDC工具在ThreadLocal中存盤和獲取traceId

public class MdcUtil {

    private static final String TRACE_ID = "TRACE_ID";

    public static String get() {
        return MDC.get(TRACE_ID);
    }

    public static void add(String value) {
        MDC.put(TRACE_ID, value);
    }
}

當然,這個例子中沒有演示MdcUtil類的add方法具體調的地方,我們可以在filter中執行介面方法之前,生成traceId,呼叫MdcUtil類的add方法添加到MDC中,然后在同一個請求的其他地方就能通過MdcUtil類的get方法獲取到該traceId,

九 統一例外處理

以前我們在開發介面時,如果出現例外,為了給用戶一個更友好的提示,例如:

@RequestMapping("/test")
@RestController
public class TestController {

    @GetMapping("/add")
    public String add() {
        int a = 10 / 0;
        return "成功";
    }
}

如果不做任何處理請求add介面結果直接報錯:

在這里插入圖片描述

what?用戶能直接看到錯誤資訊?

這種互動方式給用戶的體驗非常差,為了解決這個問題,我們通常會在介面中捕獲例外:

@GetMapping("/add")
public String add() {
        String result = "成功";
        try {
            int a = 10 / 0;
        } catch (Exception e) {
            result = "資料例外";
        }
        return result;
}

介面改造后,出現例外時會提示:“資料例外”,對用戶來說更友好,

看起來挺不錯的,但是有問題,,,

如果只是一個介面還好,但是如果專案中有成百上千個介面,都要加上例外捕獲代碼嗎?

答案是否定的,這時全域例外處理就派上用場了:RestControllerAdvice

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        if (e instanceof ArithmeticException) {
            return "資料例外";
        }
        if (e instanceof Exception) {
            return "服務器內部例外";
        }
        retur nnull;
    }
}

只需在handleException方法中處理例外情況,業務介面中可以放心使用,不再需要捕獲例外(有人統一處理了),真是爽歪歪,

十 異步也可以這么優雅

以前我們在使用異步功能時,通常情況下有三種方式:

  • 繼承Thread類
  • 實作Runable介面
  • 使用執行緒池

讓我們一起回顧一下:

繼承Thread類

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("===call MyThread===");
    }

    public static void main(String[] args) {
        new MyThread().start();
    }
}

實作Runable介面

public class MyWork implements Runnable {
    @Override
    public void run() {
        System.out.println("===call MyWork===");
    }

    public static void main(String[] args) {
        new Thread(new MyWork()).start();
    }
}

使用執行緒池

public class MyThreadPool {

    private static ExecutorService executorService = new ThreadPoolExecutor(1, 5, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200));

    static class Work implements Runnable {

        @Override
        public void run() {
            System.out.println("===call work===");
        }
    }

    public static void main(String[] args) {
        try {
            executorService.submit(new MyThreadPool.Work());
        } finally {
            executorService.shutdown();
        }

    }
}

這三種實作異步的方法不能說不好,但是spring已經幫我們抽取了一些公共的地方,我們無需再繼承Thread類或實作Runable介面,它都搞定了,

如何spring異步功能呢?

第一步,springboot專案啟動類上加@EnableAsync注解,

@EnableAsync
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args);
    }
}

第二步,在需要使用異步的方法上加上@Async注解:

@Service
public class PersonService {

    @Async
    public String get() {
        System.out.println("===add==");
        return "data";
    }
}

然后在使用的地方呼叫一下:personService.get();就擁有了異步功能,是不是很神奇,

默認情況下,spring會為我們的異步方法創建一個執行緒去執行,如果該方法被呼叫次數非常多的話,需要創建大量的執行緒,會導致資源浪費,

這時,我們可以定義一個執行緒池,異步方法將會被自動提交到執行緒池中執行,

@Configuration
public class ThreadPoolConfig {

    @Value("${thread.pool.corePoolSize:5}")
    private int corePoolSize;

    @Value("${thread.pool.maxPoolSize:10}")
    private int maxPoolSize;

    @Value("${thread.pool.queueCapacity:200}")
    private int queueCapacity;

    @Value("${thread.pool.keepAliveSeconds:30}")
    private int keepAliveSeconds;

    @Value("${thread.pool.threadNamePrefix:ASYNC_}")
    private String threadNamePrefix;

    @Bean
    public Executor MessageExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

spring異步的核心方法:

在這里插入圖片描述

根據回傳值不同,處理情況也不太一樣,具體分為如下情況:

在這里插入圖片描述

十一 聽說快取好用,沒想到這么好用

spring cache架構圖:

在這里插入圖片描述

它目前支持多種快取:

在這里插入圖片描述

我們在這里以caffeine為例,它是spring官方推薦的,

第一步,引入caffeine的相關jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.6.0</version>
</dependency>

第二步,配置CacheManager,開啟EnableCaching

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager(){
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        //Caffeine配置
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                //最后一次寫入后經過固定時間過期
                .expireAfterWrite(10, TimeUnit.SECONDS)
                //快取的最大條數
                .maximumSize(1000);
        cacheManager.setCaffeine(caffeine);
        return cacheManager;
    }
}

第三步,使用Cacheable注解獲取資料

@Service
public class CategoryService {
   
   //category是快取名稱,#type是具體的key,可支持el運算式
   @Cacheable(value = "category", key = "#type")
   public CategoryModel getCategory(Integer type) {
       return getCategoryByType(type);
   }

   private CategoryModel getCategoryByType(Integer type) {
       System.out.println("根據不同的type:" + type + "獲取不同的分類資料");
       CategoryModel categoryModel = new CategoryModel();
       categoryModel.setId(1L);
       categoryModel.setParentId(0L);
       categoryModel.setName("電器");
       categoryModel.setLevel(3);
       return categoryModel;
   }
}

呼叫categoryService.getCategory()方法時,先從caffine快取中獲取資料,如果能夠獲取到資料則直接回傳該資料,不會進入方法體,如果不能獲取到資料,則直接方法體中的代碼獲取到資料,然后放到caffine快取中,

最后說一句(求關注,別白嫖我)
如果這篇文章對您有所幫助,或者有所啟發的話,幫忙掃描下發二維碼關注一下,您的支持是我堅持寫作最大的動力,

求一鍵三連:點贊、轉發、在看,

關注公眾號:【蘇三說技術】,在公眾號中回復:面試、代碼神器、開發手冊、時間管理有超贊的粉絲福利,另外回復:加群,可以跟很多BAT大廠的前輩交流和學習,

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

標籤:java

上一篇:IDEA史上最全的各種快捷鍵

下一篇:Java程式的邏輯控制和方法

標籤雲
其他(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