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.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;
}
}