spring boot 知識點整理
最近新的項目架構啓用spring boot cloud,SO現在先坐下簡單的技術梳理,後邊的博客會把spring的技術細節,boot的技術細節重新梳理一遍
1、下面是根據條件初始化bean
2、讀取配置信息操作
加載配置可以用@PropertySource("classpath:com/ecej/test2/test.properties") 記得要用 private Environment environment; 讀取配置
packagecom.ecej.test2;
importorg.apache.commons.io.IOUtils;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.ComponentScan;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.context.support.PropertySourcesPlaceholderConfigurer;
importorg.springframework.core.env.Environment;
importorg.springframework.core.io.Resource;
@Configuration
@ComponentScan("com.ecej.test2")
@PropertySource("classpath:com/ecej/test2/test.properties")
publicclassELConfig{
@Value("I LOVE YOU")
privateString normal;
@Value("#{systemProperties['os.name']}")
privateString osName;
@Value("#{T(java.lang.Math).random() * 100.0}")
privatedoublerandomNumber;
@Value("#{demoService.another}")
privateString fromAnother;
@Value("#classpath:com/ecej/test2/test.properties")
privateResource testFile;
@Value("http://www.baidu.com")
privateResource testUrl;
@Value("${book.name}")
privateString bookName;
@Autowired
privateEnvironment environment;
@Bean
publicstaticPropertySourcesPlaceholderConfigurerpropertyConfigure(){
returnnewPropertySourcesPlaceholderConfigurer();
}
publicvoidoutputResource(){
try{
System.out.println(normal);
System.out.println(osName);
System.out.println(randomNumber);
System.out.println(fromAnother);
System.out.println(IOUtils.toString(testUrl.getInputStream()));
System.out.println(bookName);
System.out.println(environment.getProperty("book.author"));
}catch(Exception e) {
//TODO:handle exception
}
}
}
3、spring event
事件
1 、首先我們要實現ApplicationListener 實現我們自己的監聽
2、 定義我們自己的事件 通過集成ApplicationEvent實現
3、 定義config啓動
通過applicationContext 發佈事件
@Component
publicclassDemoPublisher{
@Autowired
privateApplicationContext applicationContext;
publicvoidpublish(String msg){
applicationContext.publishEvent(newDemoEvent(this, msg));
}
}
4、spring Aware
講解:bean 和spring是無耦合的,但是如果想用到spring容器的功能資源,就要你的bean知道spring的存在,這就是spring aware
5、多線程
spring通過 TaskExecutor來實現多線程併發編程。使用ThreadPoolExecutor可實現基於線程池的TaskExecutor,使用@EnableAsync開啓對異步任務的支持,並通過在實際執行bean方法中使用@Async註解來聲明一個異步任務
6、計劃任務
通過配置註解@EnableScheduline來開啓對計劃任務的支持,然後再要執行的任務上加註解@Scheduled
spring通過@Scheduled支持多種類型計劃任務,包含cron,fixDelay、fixRate(固定時間執行)
7、條件註解@Conditional
8、組合註解與源註解
源註解:就是可以註解到別的註解上的註解,被註解的註解稱之爲組合註解。組合註解有源註解的功能。
@Configuration @ComponentScan 組合出 Wiselyconfiguration
9、@Enable*註解工作原理
10、Spring MVC
下面所講解的都是配置在MyMVCConfig
通過實現WebApplicationInitializer 等同於web.xml配置
基本配置
spring MVC的定製配置需要我們配置集成一個WebMvcConfigurerAdapter,並在此使用@EnableWebMvc註解,來開啓對spring MVC配置支持
靜態資源
重寫addResourceHandlers方法實現
攔截器配置
類似servlet的Filter
可以讓普通bean 實現HanlderIntercepetor接口或者繼承HandlerInterceptorAdapter類來實現自定義攔截器
在boot中通過重寫WebMvcConfigurerAdapter 的 addInterceptors方法來註冊自定義攔截器
@ControllerAdvice
@ExceptionHandler定義全局處理 ,通過value屬性可以設置攔截過濾條件
在開發中經常會遇到跳轉頁面的事情,我們還要單獨寫一個方法很麻煩,現在可以這樣
路徑參數配置
在spring mvc中路徑參數如果帶點“.” ,那點後面的值將被忽略。通過重寫configurePathMatch(PathMatchConfigurer) 可不忽略 點後參數
文件上傳
demo集合
正式開始spring boot
CLI 命令行控制工具
1、@SpringBootApplication 和入口
這個標籤是個組合註解,包含了@Configuration @EnableAutoConfiguration @ComponentScan三個標籤
@EnableAutoConfiguration 讓spring boot根據類路徑中的jar包依賴爲當前項目進行自動配置
在spring boot中我們可以使用
@Value("${book.author}")直接注入屬性,但是還是感覺一個個注入麻煩啊,SO,我們可以直接映射一個類,用@ConfigurationProperties(prefix="author",locations={"classpath:author.properties"})通過prefix指定前綴,通過locations指定位置
2、spring boot 的web開發
需要定義模版信息的話,使用ViewResolver ,別忘了在config上加註解@EnableWebMvc
@Bean
publicInternalResourceViewResolverviewResolver(){
InternalResourceViewResolver resolver =newInternalResourceViewResolver();
resolver.setPrefix("WEB-INF/classes/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
returnresolver;
}
靜態資源默認放在src/main.resources/static 下面
3、靜態首頁的支持
4、接管spring boot 的web配置
如果boot 提供的配置不是我們需要的,可以通過配置類修改,
註解來實現自己完全控制
@Configuration
@ComponentScan("com.ecej.test.mvc")
@EnableWebMvc
如果我們想即用默認配置,又增加自定義配置,可以集成WebMvcConfigurerAdapter,無需使用@EnableWebMvc註解
5、註冊servlet Filter Listener(重點來了)
可以註冊ServletRegistrationBean FilterRegistrationBean ServletListenerRegistrationBean 的bean來實現
6、Tomcat配置
其實就是servlet容器配置,因爲BOOT內置的是tomcat,所以也就叫tomcat配置了
配置都在org.springframework.boot.autoconfigure.web.ServerProperties 中(其實大部分都有這麼個配置)
SO,我們只需要在application.properties中配置就好了(如果你想擁別的名字,只需要配置下就行咯,在上邊有提到過)。通用的配置都以server作爲前綴
例子:
配置容器
server.port=8080
server.session-timeout=2
配置tomcat
server.tomcat.uri-encoding=UTF-8
上邊都是配置文件配置,如果想玩玩代碼也是可以的,下面介紹代碼配置
想配置servlet容器可以實現一個EmbeddedServletContainerCustomizer的接口(注意聲明的類要爲static)
想直接配置tomcat等則可以直接定義TomcatEmbeddedServletContainerFactory等
7、SSL配置(安全套接層)
生成證書:
JDK下有工具keytool ,他是一個證書管理工具,可以用來生成證書
在你命令執行的當前目錄下生成了一個.keystore的證書
配置我們的配置文件
server.port=8000
server.ssl.key-store=.keystore
server.ssl.key-store-password=123456
server.ssl.keyStoreType=JKS
server.ssl.keyAlias:tomcat
此時在啓動項目就變成了https的
8、設置自己的Favicon
這個就非常簡單了,只需要將自己的favicon.ico文件放在META-INF/resources/ resources/ static/ public/下面任意一個目錄下就行了。
9、WebSocket
這到底是個什麼鬼呢?
官方說法,就是爲瀏覽器和服務端提供雙工異步通信的功能。直接使用WebSocket會使開發非常繁瑣的,所以我們使用它的子協議STOMP,它是一個更高級的協議,STOMP協議使用一個基於幀的格式來定義消息,與HTTP的request response類似。
spring boot內置了這玩意,可以看websocket包下的類
需要加入
spring-boot-starter-websocket 包
@EnableWebSocketMessageBroker註解並繼承AbstractWebSocketMessageBrokerConfigurer
模式:
廣播式 會將消息發送給所有連接了當前的瀏覽器
代碼片段
packagecom.ecej.demo2.websocket;
importorg.springframework.context.annotation.ComponentScan;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.messaging.simp.config.MessageBrokerRegistry;
importorg.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
importorg.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
importorg.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@ComponentScan(value ="com.ecej.demo2.websocket")
@EnableWebSocketMessageBroker
publicclassWebSocketConfigextendsAbstractWebSocketMessageBrokerConfigurer{
@Override
publicvoidregisterStompEndpoints(StompEndpointRegistry register){
register.addEndpoint("/endpointWisely").withSockJS();
}
@Override
publicvoidconfigureMessageBroker(MessageBrokerRegistry register){
register.enableSimpleBroker("/topic");
}
}
解析:
1、通過@EnableWebSocketMessageBroker 註解開啓使用STOMP協議傳輸基於代理(message broker)的消息,
這時控制器支持使用@MessageMapping,就像使用@RequestMapping一樣
2、註冊STOMP協議的節點,並映射的指定的URL
3、註冊一個STOMP的endpoint,並指定使用SocketJS協議
4、配置消息代理(message broker)
5、廣播式應配置一個/topic消息代理
10、spring 的事物機制
spring事物機制提供了一個PlatformTransactionManager接口,不同的數據訪問技術的事物使用不同的接口實現
聲明式事物
使用@Transactional註解在方法上表明該方法需要事物支持,基於AOP實現操作。
使用@EnableTransactionManagement來開啓上邊的註解
類級別的註解@Transactional會重載方法級別的
11、緩存支持
不同的緩存技術,需要不同的cacheManager
12、異步消息
spring 對JMS和AMQP的支持分別來自於spring-jms 和spring-rabbit
他們分佈需要ConnectionFactory來實現連接消息代理,並分別提供了JmsTemplate、RabbitTemplate
spring爲JMS 、AMQP提供了@JmsListener @RabbitListener 註解在方法上監聽消息代理髮布的消息。我們只需要分別通過@EnableJms @EnableRabbit開啓支持
原文:https://blog.csdn.net/luqiang81191293/article/details/54629873