第十五章、Spring Boot 知識點3

課時六十七、Spring Boot Freemarker特別篇之contextPath

(1)問題的提出

我們有時候需要在freemarker模板文件.ftl中獲取contextPath,如果沒有配置一些參數的話,那麼是無法進行獲取的。

(2)spring中是如何定義requestContextAttribute的

在spring 中是使用配置文件的方法進行配置指定的,如下:

<property name="requestContextAttribute" value="request"/>

    配置完之後,我們就可以在我們的x.ftl文件中使用如下代碼進行
引入使用:
${request.contextPath}。
 

(3)Spring Boot應該如何定義呢

                 

(4)有更好的解決方案嘛?

以上方式雖然也能解決問題,但是總覺得繞了一個圈子,我們原本使用freemarker的時候,我們使用的是在配置文件application.properties文件進行使用的,現在又回到了代碼的方式去引入了,那麼要思考下我們可不可以在application.properties進行直接指定呢,答案是可以的。我們只需要在application.properties中添加如下配置:
    spring.freemarker.request-context-attribute=request
    那麼就可以在ftl文件中進行使用${request.contextPath}了。

(5)總結

本文說了這麼說,其實很簡單就兩個步驟:

1、在application.properties添加如下信息:
spring.freemarker.request-context-attribute=request

2、在x.ftl文件中進行使用:
${request.contextPath}

課時六十八、Spring Boot打印所有Spring載入的bean

問題引入

我們在開發過程當中,我們可能會碰到這樣的問題:No qualifying bean  就是我們定義的bean無法進行注入,那到底是什麼原因呢,有時候挺難定位的,當然這個也需要養成良好的編碼習慣,這樣也會降低出錯的機率。 那麼一般說是No quanlifying bean很有可能就是我們沒有使用註解或者xml注入我們的bean,要麼就是我們bean的名稱不是我們注入時指定的名稱,那麼我們就會想如何查看已經載入到spring boot的bean呢?
其實這個操作起來很簡單,看如下介紹知道了。

第一種情況獲取所有的beans

ApplicationContext  ctx =  SpringApplication.run(App.class, args);
        String[] beanNames =  ctx.getBeanDefinitionNames();
        System.out.println("所以beanNames個數:"+beanNames.length);
        for(String bn:beanNames){
            System.out.println(bn);
        }

第二種情況獲取我們指定的註解類

/**
         * @Service
         * @RestController
         * @Componment

         * **/
        String[] beanNames1 =  ctx.getBeanNamesForAnnotation(RestController.class);
        System.out.println("RestController:"+beanNames1.length);
        for(String bn:beanNames1){
            System.out.println(bn);
        }
    }

參考:spring-boot-jersey

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章