springboot2筆記

1.Servlet

使用@ServletComponentScan+@WebServlet注解實現(xiàn)

  • 定義一個類用@WebServlet(urlPatterns = "url路徑")注解修飾;
    urlPatterns表示映射的url路徑
  • 新創(chuàng)建的類繼承HttpServlet類,可以重寫里面的doGet等方法翼岁;
  • @ServletComponentScan(basePackages = "包路徑")使用該注解來進行組件掃描。

注解掃描類似與SpringMVC里面的<context:component-scan>標簽忧风。

在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter招刨、Listener可以直接通過@WebServlet夹供、@WebFilter灵份、@WebListener注解自動注冊,無需其他代碼哮洽。

2.異步處理

2.1 AsyncContext

  • AsyncContext asyncContext = req.startAsync();
  • asyncContext.start() 來開啟異步事件填渠;
  • 必須要在@WebServlet或@WebFilter上加入asyncSupported=true,@WebServlet默認異步是不支持的鸟辅;
  • 對客戶端的響應將暫緩至調用AsyncContext的complete()或dispatch()方法為止(也就是必須等待調用這兩個方法結束才能停止客戶端響應)氛什。

2.2 @EnableAsync+@Async

@Service
public class AsyncService {

    //告訴spring 這是一個異步的
    @Async
    public void hello()  {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("處理數(shù)據(jù)中!");
    }
}

3.切換Servlet容器

  • 首先把在spring-boot-starter-web中tomcat給排除掉匪凉;
  • 在外部添加相應的依賴枪眉。

4.Spring模式注解裝配

定義:一種用于聲明在應用在扮演“組件”角色的注解
舉例:@Component,@Service再层,@Configuration
裝配:<context:component-scan>或@ComponentScan

5.SpringBoot自動掃描包

@SpringBootApplication > @EnableAutoConfiguration > @AutoConfigurationPackage > @Import({Registrar.class})

在Registrac類下有一個方法:
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {

        AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
    }

該方法中指定了自動掃描的包默認就是當前@SpringBootApplication注解所使用的類包瑰谜。

6.配置文件值自動注入

  • 首先創(chuàng)建一個合法的bean類;
  • 在application.yml或application.properties文件中根據(jù)相應的屬性值進行賦值树绩;
  • 在bean類上加上@ConfigurationProperties(prefix = "person") (默認從全局配置文件中找

告訴SpringBoot將本類中的所有屬性和配置文件中相關的進行綁定 ,并且指定是在配置文件下面的哪些屬性進行一一映射

  • 在@ConfigurationProperties上面加上@Component注解萨脑。

只有這個組件是容器中的組件,才能使用容器提供的@ConfigurationProperties功能饺饭;

只有在pom文件中添加了下面的依賴關系渤早,才可以在yml文件中有相應的提示功能。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

在利用yml進行自動注入時實際調用的是類的無參構造函數(shù)和set方法

7.利用@Value()進行屬性值填充

支持字面量${}從環(huán)境變量和配置文件中獲取值瘫俊,#{SpEL}鹊杖。

@Value只能用于基礎類型,不能用于復雜類型扛芽。

8.@PropertySource & @ImportResource

  • @PropertySource:加載指定的配置文件
@PropertySource(value={"classpath:person.properties"})
@Component 
@ConfigurationProperties(prefix = "person")
  • @ImportResource:導入Spring的配置文件骂蓖,讓配置文件中的內(nèi)容生效。

在主類上可以加上@ImportResource(locations = {"classpath:applicationContext.xml"})來使我們的配置文件生效川尖。

Spring推薦使用@Bean注解來配置:

@Configuration
public class MyAppCinfig {

    @Bean
    public HelloService helloService(){
        System.out.println("通過方法配置bean");
        return new HelloService();
    }

}

9.配置文件默認值登下?

  • 隨機數(shù):{random.uuid},{random.int}
  • 占位符獲取之前配置的值,如果沒有可以使用“:”指定默認值:${person.name:name}

10.Profile

10.1 多個Profile文件:

配置文件名為application-{profile}.properties/yml被芳。
默認使用application.properties文件缰贝。

application-dev.properties配置文件:server.port=8081
application-prod.properties配置文件:server.port=8082

10.2 yml支持多文檔塊方式

server:
  port: 8080
spring:
  profiles:
    active: prod

---
server:
  port: 8081
spring:
  profiles:dev
---

server:
  port: 8082
spring:
  profiles:prod
---

10.3激活指定profile

  • 在配置文件中指定spring.profiles.active=dev
  • 在命令行中添加:--spring.profiles.active=prod

Edit Configurations -> Program arguments -> --spring.profiles.active=prod

打包成jar文件,在cmd中用命令執(zhí)行:java -jar springboot2demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

  • 虛擬機參數(shù):> Edit Configurations -> VM options -> -Dspring.profiles.active=dev

11 獲得啟用的自動配置

debug = true 會在控制臺輸出Positive matches信息畔濒。

12 日志

spring框架用的是JCL剩晴,SpringBoot框架用的是SLF4J和logback。

在引入其他框架的時候只需將框架的日志文件排除掉侵状。

Logger logger = LoggerFactory.getLogger(getClass());
        logger.trace("這是trace日志赞弥。。趣兄。嗤攻。");
        logger.debug("這是debug日志。诽俯。。承粤。");
        logger.info("這是info日志暴区。。辛臊。仙粱。");
        logger.warn("這是warn日志。彻舰。伐割。");
        logger.error("這是error日志。刃唤。隔心。");

日志的級別由低到高:trace<debug<info<warn<error。
SpringBoot默認只能輸出info及以上級別的信息尚胞。

可以在屬性文件中進行輸出級別的調整:logging.level.com.springboot2test=trace

  • logging.file:在指定路徑下生成指定日志文件硬霍。
  • logging.path:在指定目錄下生成spring.log日志文件。

13 靜態(tài)資源文件映射

        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }
  • 所有/webjars/**訪問路徑都去classpath:/META-INF/resources/webjars/下找資源笼裳。

webjars依賴查詢網(wǎng)址:https://www.webjars.org/

@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
  • “/**”可以訪問的路徑(靜態(tài)文件夾):

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/

  • 歡迎頁:靜態(tài)資源文件夾下的所有index.html頁面唯卖,被“/**”映射。
  • 所有的**/favicon.ico都是在靜態(tài)資源文件下找躬柬。
  • spring.resources.static-locations來進行資源自定義(會禁止原先的資源設置)拜轨。

14 Thymeleaf

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/"; 
    public static final String DEFAULT_SUFFIX = ".html";   //后綴

只要把html頁面放在classpath:/templates/路徑下,Thymeleaf就會自動渲染允青。

  • 導入名稱空間:<html lang="en" xmlns:th="http://www.thymeleaf.org">

15 JPA

  • 導入相應依賴
        <!-- jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

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

        <!-- mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
  • 配置屬性文件
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/jpatest?charset=utf8mb4&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: root
    password: ljcgit123
    driver-class-name: com.mysql.cj.jdbc.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
  • 創(chuàng)建實體類
  • 創(chuàng)建實體相應的Repository

注意點:

16 緩存

16.1 基本使用

  • 首先添加基本依賴
        <!-- cache -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
  • 在Application類上開啟緩存:

@EnableCaching //開啟緩存

  • 在相應的方法上添加@Cacheable注解

注意點:

  • 在屬性中使用了@Autowired注解的類橄碾,如果通過new來生成實例的話,使用了@Autowired注解的屬性會為null(不報錯)
  • 必須給@Cacheable注解添加cacheNames屬性值堪嫂。

16.2 屬性講解

  • cacheName/value :指定緩存組件的名字偎箫。
  • key:緩存數(shù)據(jù)使用的key。默認是使用方法參數(shù)的值皆串。
  • keyGenerator:key的生成器淹办;可以自己指定key的生成器的組件id。(key/keyGenerator:兩選一使用)恶复。
  • cacheManager:指定緩存管理器怜森。
  • cachResolver指定獲取解析器。
  • condition:指定符合條件的情況下才緩存谤牡。
  • unless:當指定條件為true時副硅,方法的返回值不會被緩存。
  • sync:是否使用異步模式翅萤。

16.3 @CachePut 修改緩存值

該注解屬性和@Cacheable屬性值一樣恐疲,在使用時需要確保和緩存中的key一致。

16.4 @CacheEvict 刪除緩存值

  • allEntries :指定是否清除這個緩存中的所有數(shù)據(jù)套么,默認false培己。
  • beforeInvocation :清除緩存是否在方法執(zhí)行之前執(zhí)行,默認false胚泌,表示會在該方法執(zhí)行之后執(zhí)行省咨,如果出現(xiàn)異常就不會執(zhí)行。

16.5 @Caching 組合注解

16.6 @CacheConfig 公共注解

17 Redis緩存

在SpringBoot中默認使用的是ConcurrentMapCacheManager玷室。

自定義RedisTemplate

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, User> myredisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, User> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<User> jk=new Jackson2JsonRedisSerializer<User>(User.class);
        template.setDefaultSerializer(jk);
        return template;
    }
}
    @Autowired
    RedisTemplate<Object, User> myredisTemplate;

java.util.LinkedHashMap cannot be cast to com.springboot2test.springboot2demo.bean.User] with root cause

18 RabbitMQ

  • Message:消息零蓉,由消息頭和消息體組成。消息體是不透明的穷缤,而消息頭則由一系列的可選屬性組成敌蜂,包括routing-key(路由鍵),priority(相對于其他消息的優(yōu)先權)津肛,delivery-mode(指出該消息可能需要持久性存儲)等紊册。
  • Publisher:消息的生產(chǎn)者,也是一個向交換器發(fā)布消息的客戶端應用程序快耿。
  • Exchange:交換器囊陡,用來接收生產(chǎn)者發(fā)送的消息并將這些消息路由給服務器中的隊列。

Exchange有4種類型:direct(默認)掀亥,fanout撞反,topic,headers搪花。
direct:單播
fanout:廣播
topic:按指定樣式

  • Queue:消息隊列遏片。一個消息可投入一個或多個消息隊列嘹害,消息一直在隊列里面,等待消費者連接到這個隊列將其取走吮便。
  • Binding:用于消息隊列和交換器之間的關聯(lián)笔呀。
  • Connection:網(wǎng)絡連接。
  • Channel:信道髓需。
  • Consummer:消息的消費者许师。
  • Virtual Host:虛擬主機。每個vhost本質上就是一個mini版的RabbitMQ服務器僚匆,擁有自己的隊列微渠,交換器,綁定和權限機制咧擂。默認是/逞盆。
  • Broker:消息隊列服務器實體。

18.1配置RabbitMQ基本環(huán)境(docker)

  • 在docker中pull相應鏡像:

docker pull registry.docker-cn.com/library/rabbitmq:3-management
registry.docker-cn.com/library/ 是國內(nèi)鏡像加速地址松申;
3-management標簽表示具有管理界面云芦。

  • 啟動鏡像:

docker run -p 5672:5672 -p 15672:15672 --name myrabbitmq -d 24cb552c7c00
將5672(客戶端通信端口)和15672(管理端口)暴露出來,同時作為一個守護進程在后臺運行贸桶。
訪問管理頁面:ip:15672 (默認賬號密碼都是guest)舅逸。

18.2利用RabbitTemplete發(fā)送消息

  • 導入ampq依賴:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
  • 設置配置屬性值
spring.rabbitmq.host=id
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
  • send():需要自己構建一個Message消息體。
    convertAndSend():只要傳入一個對象刨啸,就會自動進行轉換。
        Map<String,Object> maps=new HashMap<>();
        maps.put("msg","這是一個消息识脆!");
        maps.put("data", Arrays.asList("ljc",1234,true));
        rabbitTemplate.convertAndSend("exchanges.direct","springboot",maps);

在以對象為信息發(fā)送的時候设联,對象會被默認序列化。

  • 接收消息
        Object o = rabbitTemplate.receiveAndConvert("springboot");
        System.out.println(o.getClass());
        System.out.println(o);

接收完消息后隊列中就不存在了灼捂。

  • 設置發(fā)送轉換類型(JSON):
@Configuration
public class MyAMQPConfig {

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}

18.3 @EnableRabbit+@RabbitListener監(jiān)聽消息

@Service
public class UserAmpqService {

    @RabbitListener(queues = "springboot")
    public void receive(User user){
        System.out.println(user);
    }
}

當消息隊列中有消息進入离例,系統(tǒng)就會自動獲取到消息。
或者利用Message作為參數(shù)來獲取更多的消息信息悉稠。

19 定時任務

@EnableScheduling + @Scheduled

@Service
public class ScheduledService {

    @Scheduled(cron = "0 * * * * MON-SAT")
    public void hello(){
        System.out.println("hello");
    }
}

20 設置過濾器

20.1 利用spring注解實現(xiàn)

  • 開啟容器掃描注解:@ServletComponentScan(value="com.xssdemo.xsstest.filer")
  • 在過濾器上寫上@WebFilter(urlPatterns = "/*")注解

20.2 提供Bean的方式

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(new XSSFilter());
        registrationBean.setName("myFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宫蛆,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子的猛,更是在濱河造成了極大的恐慌耀盗,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,888評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件卦尊,死亡現(xiàn)場離奇詭異叛拷,居然都是意外死亡,警方通過查閱死者的電腦和手機岂却,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評論 3 399
  • 文/潘曉璐 我一進店門忿薇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來裙椭,“玉大人,你說我怎么就攤上這事署浩∪嗳迹” “怎么了?”我有些...
    開封第一講書人閱讀 168,386評論 0 360
  • 文/不壞的土叔 我叫張陵筋栋,是天一觀的道長炊汤。 經(jīng)常有香客問我,道長二汛,這世上最難降的妖魔是什么婿崭? 我笑而不...
    開封第一講書人閱讀 59,726評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮肴颊,結果婚禮上氓栈,老公的妹妹穿的比我還像新娘。我一直安慰自己婿着,他們只是感情好授瘦,可當我...
    茶點故事閱讀 68,729評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著竟宋,像睡著了一般提完。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上丘侠,一...
    開封第一講書人閱讀 52,337評論 1 310
  • 那天徒欣,我揣著相機與錄音,去河邊找鬼蜗字。 笑死打肝,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的挪捕。 我是一名探鬼主播粗梭,決...
    沈念sama閱讀 40,902評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼级零!你這毒婦竟也來了断医?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,807評論 0 276
  • 序言:老撾萬榮一對情侶失蹤奏纪,失蹤者是張志新(化名)和其女友劉穎鉴嗤,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體序调,經(jīng)...
    沈念sama閱讀 46,349評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡躬窜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,439評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了炕置。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片荣挨。...
    茶點故事閱讀 40,567評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡男韧,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出默垄,到底是詐尸還是另有隱情此虑,我是刑警寧澤,帶...
    沈念sama閱讀 36,242評論 5 350
  • 正文 年R本政府宣布口锭,位于F島的核電站朦前,受9級特大地震影響,放射性物質發(fā)生泄漏鹃操。R本人自食惡果不足惜韭寸,卻給世界環(huán)境...
    茶點故事閱讀 41,933評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望荆隘。 院中可真熱鬧恩伺,春花似錦、人聲如沸椰拒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,420評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽燃观。三九已至褒脯,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間缆毁,已是汗流浹背番川。 一陣腳步聲響...
    開封第一講書人閱讀 33,531評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留脊框,地道東北人颁督。 一個月前我還...
    沈念sama閱讀 48,995評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像缚陷,于是被迫代替她去往敵國和親适篙。 傳聞我的和親對象是個殘疾皇子往核,可洞房花燭夜當晚...
    茶點故事閱讀 45,585評論 2 359

推薦閱讀更多精彩內(nèi)容