1.springboot 常用接口

1.1 Aware接口

Spring IOC容器中 Bean是感知不到容器的存在,Aware(意識到的)接口就是幫助Bean感知到IOC容器的存在,即獲取當前Bean對應的Spring的一些組件,如當前Bean對應的ApplicationContext等。

1.1.1 ApplicationContextAware 獲取ApplicationContext

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public SpringContextUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<?> clz) throws BeansException {
        return applicationContext.getBean(clz);
    }
}

1.1.2 EnvironmentAware 環境變量讀取和屬性對象獲取

關於Enviroment作用:

Environment:環境,Profile 和 PropertyResolver 的組合。
Environment 對象的作用是確定哪些配置文件(如果有)當前處於活動狀態,以及默認情況下哪些配置文件(如果有)應處於活動狀態。
properties 在幾乎所有應用程序中都發揮着重要作用,並且有多種來源:屬性文件,JVM 系統屬性,系統環境變量,JNDI,
servlet 上下文參數,ad
-hoc 屬性對象,映射等。同時它繼承 PropertyResolver 接口,
所以與屬性相關的 Environment 對象其主要是為用於配置屬性源和從中屬性源中解析屬性。
@Component
 public class MyEnvironment implements EnvironmentAware {
    private Environment environment;
    @Override
    public void setEnvironment(Environment environment) {
           this.environment=environment;
    }
 }

Aware的其他子接口

ApplicationEventPublisherAware (org.springframework.context):事件發布
用法可參考:ApplicationEventPublisherAware事件發布詳解 ServletContextAware (org.springframework.web.context): ServletContext
ServletConfigAware (org.springframework.web.context): ServletConfig
用法可參考:ServletConfig與ServletContext接口API詳解和使用
MessageSourceAware (org.springframework.context): 國際化
用法可參考:Spring的國際化資源messageSource ResourceLoaderAware (org.springframework.context):訪問底層資源的加載器
用法參考:Spring使用ResourceLoader接口獲取資源 NotificationPublisherAware (org.springframework.jmx.export.notification):JMX通知
Spring JMX之一:使用JMX管理Spring Bean: https://www.cnblogs.com/duanxz/p/3968308.html
Spring JMX之三:通知的處理及監聽: https://www.cnblogs.com/duanxz/p/4036619.html BeanFactoryAware (org.springframework.beans.factory): 申明BeanFactory Spring BeanFactory體系: https://juejin.cn/post/6844903881890070541
EmbeddedValueResolverAware (org.springframework.context): 手動讀取配置
使用方式可以參考:
Spring中抽象類中使用EmbeddedValueResolverAware和@PostConstruct獲取配置文件中的參數值
ImportAware (org.springframework.context.annotation):處理自定義注解
關於ImportAware的作用可以看: Spring的@Import注解與ImportAware接口 BootstrapContextAware (org.springframework.jca.context): 資源適配器BootstrapContext,如JAC,CCI
springcloud情操陶冶-bootstrapContext(二): https://blog.csdn.net/weixin_30725467/article/details/96008648 LoadTimeWeaverAware (org.springframework.context.weaving):加載Spring Bean時植入第三方模塊,如AspectJ
說說在 Spring AOP 中如何實現類加載期織入(LTW): https://juejin.cn/post/6844903664469950478 BeanClassLoaderAware (org.springframework.beans.factory): 加載Spring Bean的類加載器 深入理解Java類加載器(ClassLoader): https://blog.csdn.net/javazejian/article/details/73413292
BeanNameAware (org.springframework.beans.factory): 申明Spring Bean的名字
ApplicationContextAware (org.springframework.context):申明ApplicationContext

1.2 ApplicationEvent ApplicationListener 自定義事件,及監聽

如果容器中存在ApplicationListener的Bean,當ApplicationContext調用publishEvent方法時,對應的Bean會被觸發。

spring內置事件

內置事件 描述
ContextRefreshedEvent       ApplicationContext 被初始化或刷新時,該事件被觸發。這也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法來發生。此處的初始化是指:所有的Bean被成功裝載,后處理Bean被檢測並激活,所有Singleton Bean 被預實例化,ApplicationContext容器已就緒可用
ContextStartedEvent         當使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法啟動 ApplicationContext 時,該事件被發布。你可以調查你的數據庫,或者你可以在接受到這個事件后重啟任何停止的應用程序。
ContextStoppedEvent       當使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 時,發布這個事件。你可以在接受到這個事件后做必要的清理的工作。
ContextClosedEvent        當使用 ConfigurableApplicationContext 接口中的 close() 方法關閉 ApplicationContext 時,該事件被發布。一個已關閉的上下文到達生命周期末端;它不能被刷新或重啟。
RequestHandledEvent     這是一個 web-specific 事件,告訴所有 bean HTTP 請求已經被服務。只能應用於使用DispatcherServlet的Web應用。在使用Spring作為前端的MVC控制器時,當Spring處理用戶請求結束后,系統會自動觸發該事件。

 同樣事件可以自定義、監聽也可以自定義

@Component
public class BrianListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("容器 init Bean數量:" + event.getApplicationContext().getBeanDefinitionCount());
    }

}

1.3 InitializingBean接口 

InitializingBean 為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是實現該接口的類,在初始化bean的時候會執行該方法。效果等同於bean的init-method屬性的使用或者@PostContsuct注解的使用。

三種方式的執行順序:@PostContsuct -> 執行InitializingBean接口中定義的方法 -> 執行init-method屬性指定的方法。

@Component
public class TestInitializingBean implements InitializingBean{
    @Override
    public void afterPropertiesSet() throws Exception {
       //bean 初始化后執行
    }
}

1.4 BeanPostProcessor接口

實現BeanPostProcessor接口的類即為Bean后置處理器,Spring加載機制會在所有Bean初始化的時候遍歷調用每個Bean后置處理器。BeanPostProcessor 為每個bean實例化時提供個性化的修改,做些包裝等。
其順序為:Bean實例化 -> 依賴注入 -> Bean后置處理器 (postProcessBeforeInitialization)  -> @PostConstruct  ->  InitializingBean實現類 -> 執行init-method屬性指定的方法 -> Bean后置處理器 (postProcessAfterInitialization) 

public class MyBeanPostProcessor implements BeanPostProcessor {
    /**
     * 在bean實例化之前回調
     */
    public Object postProcessBeforeInitialization(Object bean, String beanName)throws BeansException {
        System.out.println("postProcessBeforeInitialization: " + beanName);
        return bean;
    }

    /**
     * 在bean實例化之后回調
     */
    public Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {
        System.out.println("postProcessAfterInitialization: " + beanName);
        return bean;
    }
}

用法可以參考:SpringBoot之自定義注解(基於BeanPostProcessor接口實現)   SpringBoot利用注解方式接口權限過濾

1.5 BeanFactoryPostProcessor接口

bean工廠的bean屬性處理容器,說通俗一些就是可以管理我們的bean工廠內所有的beandefinition(未實例化)數據,可以隨心所欲的修改屬性

 
              
@Component
@Slf4j
public class BrianBeanFactoryPostProcessor implements BeanFactoryPostProcessor { 

  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    BeanDefinition bd
= beanFactory.getBeanDefinition("brianBean");
    MutablePropertyValues pv
= bd.getPropertyValues();

    if (pv.contains("kawa")) {
      pv.addPropertyValue(
"kawa", "修改屬性kawa的值");
    }
    }
   }

用法可以參考:Spring拓展接口之BeanFactoryPostProcessor,占位符與敏感信息解密原理     Spring的BeanFactoryPostProcessor和BeanPostProcessor  

 1.6 CommandLineRunner 和 ApplicationRunner接口

CommandLineRunner 及 ApplicationRunner 都可實現在項目啟動后執行操作別ApplicationRunner會封裝命令行參數,可以很方便地獲取到命令行參數和參數值

@Component
@Slf4j
@Order(value = 2)
public class InitServiceConfiguration implements CommandLineRunner {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        Map<String, AbstractInitService> serviceMap = applicationContext.getBeansOfType(AbstractInitService.class);
        if (serviceMap == null) {
            return;
        }
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (Map.Entry<String, AbstractInitService> entry : serviceMap.entrySet()) {
            log.info("初始化:{}", entry.getKey());
            fixedThreadPool.execute(entry.getValue());
        }
        fixedThreadPool.shutdown();
    }
}

 用法可參考:SpringBoot中CommandLineRunner和ApplicationRunner接口解析和使用

 另外這個也可以看一下,spring 比較常用且很好用的接口: https://blog.csdn.net/u011320740/article/details/105326468

2.springBoot 常用工具類

此處的匯總也包含spring常用的工具類

2.1 字符串工具類 org.springframework.util.StringUtils

首字母大寫: public static String capitalize(String str)

首字母小寫:public static String uncapitalize(String str)

判斷字符串是否為null或empty: public static boolean hasLength(String str)

判斷字符串是否為非空白字符串(即至少包含一個非空格的字符串):public static boolean hasText(String str)

獲取文件名:public static String getFilename(String path) 如e.g. "mypath/myfile.txt" -> "myfile.txt"

獲取文件擴展名:public static String getFilenameExtension(String path) 如"mypath/myfile.txt" -> "txt"

還有譬如數組轉集合、集合轉數組、路徑處理、字符串分離成數組、數組或集合合並為字符串、數組合並、向數組添加元素等。

2.2 對象序列化工具類 org.springframework.util.SerializationUtils

public static byte[] serialize(Object object)

public static Object deserialize(byte[] bytes)

2.3 數字處理工具類 org.springframework.util.NumberUtils

字符串轉換為Number並格式化,包括具體的Number實現類,如Long、Integer、Double,字符串支持16進制字符串,並且會自動去除字符串中的空格:

​ public static <T extends Number> T parseNumber(String text, Class<T> targetClass)

​ public static <T extends Number> T parseNumber(String text, Class<T> targetClass, NumberFormatnumberFormat)

各種Number中的轉換,如Long專為Integer,自動處理數字溢出(拋出異常):

public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass)

2.4 文件復制工具類 org.springframework.util.FileCopyUtils

流與流之間、流到字符串、字節數組到流等的復制

2.5 目錄復制工具類 org.springframework.util.FileSystemUtils

遞歸復制、刪除一個目錄

2.6 MD5加密 工具類org.springframework.util.DigestUtils

字節數組的MD5加密 public static String md5DigestAsHex(byte[] bytes)

2.7 ResourceUtils

org.springframework.util.xml.ResourceUtils 用於處理表達資源字符串前綴描述資源的工具. 如: "classpath:".有 getURL, getFile, isFileURL, isJarURL, extractJarFileURL

2.8 org.springframework.core.annotation.AnnotationUtils 處理注解

Spring:AnnotationUtils工具類與注解參數說明: https://blog.csdn.net/qq_26869339/article/details/91386372

2.9 org.springframework.core.io.support.PropertiesLoaderUtils 加載Properties資源工具類,和Resource結合

Spring工具類之PropertiesLoaderUtils:  https://juejin.cn/post/6844904049913888776

2.10 org.springframework.boot.context.properties.bind.Binder

Springboot 2.x新引入的類,負責處理對象與多個ConfigurationPropertySource(屬性)之間的綁定。比Environment類好用很多,可以非常方便地進行類型轉換,以及提供回調方法介入綁定的各個階段進行深度定制

Spring Boot中的屬性綁定的實現  https://segmentfault.com/a/1190000018793404

2.11 org.springframework.core.NestedExceptionUtils

NestedExceptionUtils.getMostSpecificCause(e);
NestedExceptionUtils.getRootCause(e);

2.12 xml工具類

org.springframework.util.xml.AbstractStaxContentHandler
org.springframework.util.xml.AbstractStaxXMLReader
org.springframework.util.xml.AbstractXMLReader
org.springframework.util.xml.AbstractXMLStreamReader
org.springframework.util.xml.DomUtils
org.springframework.util.xml.StaxUtils
org.springframework.util.xml.TransformerUtils

2.13 web工具類

org.springframework.web.util.CookieGenerator
org.springframework.web.util.HtmlCharacterEntityDecoder
org.springframework.web.util.HtmlCharacterEntityReferences
org.springframework.web.util.HtmlUtils
org.springframework.web.util.JavaScriptUtils
[Java工具類]spring常用工具類 2.特殊字符轉義和方法入參檢測工具類: https://blog.csdn.net/aya19880214/article/details/50550344
org.springframework.web.util.HttpUrlTemplate  這個類用於用字符串模板構建url, 它會自動處理url里的漢字及其它相關的編碼. 在讀取別人提供的url資源時, 應該經常用

org.springframework.web.util.Log4jConfigListener 用listener的方式來配制log4j在web環境下的初始化
org.springframework.web.util.UriTemplate
org.springframework.web.util.UriUtils 處理uri里特殊字符的編碼
org.springframework.web.util.WebUtils
org.springframework.web.bind.ServletRequestUtils
介紹Spring WebUtils 和 ServletRequestUtils: https://blog.csdn.net/neweastsun/article/details/80873994

2.14 其它工具集

org.springframework.util.AntPathMatcher   ant風格的處理(uri路徑匹配使用較多)
org.springframework.util.AntPathStringMatcher
詳情參考:https://blog.csdn.net/fsociety/article/details/108368590
org.springframework.util.Assert 斷言工具類(經常用到)
詳情參考:https://www.jianshu.com/p/dea1bb7bc5fe

org.springframework.util.ClassUtils Class的處理(isPresnt()方法經常用到)
詳情參考:https://blog.csdn.net/wolfcode_cn/article/details/80660552
org.springframework.util.CollectionUtils 集合的工具(不用多介紹了)
org.springframework.util.CommonsLogWriter (不常用到)
用例參考:http://www.java2s.com/example/java-api/org/springframework/util/commonslogwriter/commonslogwriter-1-0.html
org.springframework.util.CompositeIterator (復合的Iterator)
用法根簡單,看下源碼就知道它的用法
org.springframework.util.ConcurrencyThrottleSupport (控制線程數量)
詳情參考:https://www.cnblogs.com/duanxz/p/9435873.html
org.springframework.util.CustomizableThreadCreator (自定義Thread組)
org.springframework.util.LinkedCaseInsensitiveMap key值不區分大小寫的LinkedMap org.springframework.util.LinkedMultiValueMap 一個key可以存放多個值的LinkedMap
org.springframework.util.Log4jConfigurer 一個log4j的啟動加載指定配制文件的工具類 org.springframework.util.ObjectUtils 有很多處理null object的方法. 如nullSafeHashCode, nullSafeEquals, isArray, containsElement, addObjectToArray, 等有用的方法
org.springframework.util.PatternMatchUtils spring里用於處理簡單的匹配. 如 Spring
's typical "xxx", "xxx" and "xxx" pattern styles
org.springframework.util.PropertyPlaceholderHelper 用於處理占位符的替換
org.springframework.util.ReflectionUtils 反映常用工具方法. 有 findField, setField, getField, findMethod, invokeMethod等有用的方法 org.springframework.util.StopWatch 一個很好的用於記錄執行時間的工具類, 且可以用於任務分階段的測試時間. 最后支持一個很好看的打印格式. 這個類應該經常用
org.springframework.util.SystemPropertyUtils
org.springframework.util.TypeUtils 用於類型相容的判斷. isAssignable
org.springframework.util.WeakReferenceMonitor 弱引用的監控



java.util.Properties 加載文件資源
詳細參考:https://blog.csdn.net/qq_38872310/article/details/81700712
 

spring好用的的工具類集中在org.springframework.util這個包下,沒事可以多翻一翻,下面也是別人總結的工具類可以看一看

spring 常用工具類: https://www.pdai.tech/md/develop/package/dev-package-x-spring-util.html

3.springBoot 常用注解

3.1 spirngboot常用注解

@Component可配合CommandLineRunner使用,在程序啟動后執行一些基礎任務。

@JsonBackReference解決嵌套外鏈問題。
解決Json 無線遞歸問題注解@JsonBackReference該注解 加在GET SET方法頭上: https://blog.csdn.net/weixin_45029961/article/details/109026387
@RepositoryRestResourcepublic配合spring
-boot-starter-data-rest使用。 @EnableAutoConfiguration:Spring Boot自動配置(auto-configuration):嘗試根據你添加的jar依賴自動配置你的Spring應用。
例如,如果你的classpath下存在HSQLDB,並且你沒有手動配置任何數據庫連接beans,那么我們將自動配置一個內存型(in-memory)數據庫,
你可以將@EnableAutoConfiguration或者@SpringBootApplication注解添加到一個@Configuration類上來選擇自動配置。
如果發現應用了你不想要的特定自動配置類,你可以使用@EnableAutoConfiguration注解的排除屬性來禁用它們。 @ComponentScan:表示將該類自動發現掃描組件。個人理解相當於,如果掃描到有@Component、@Controller、@Service等這些注解的類,
並注冊為Bean,可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,並結合@Autowired注解導入。
可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,並結合@Autowired注解導入。
如果沒有配置的話,Spring Boot會掃描啟動類所在包下以及子包下的使用了@Service,@Repository等注解的類。 @Import:用來導入其他配置類。 @ImportResource:用來加載xml配置文件。 @Inject:等價於默認的@Autowired,只是沒有required屬性; @Qualifier:當有多個同一類型的Bean時,可以用@Qualifier(“name”)來指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據名字進行注入,但能進行更細粒度的控制如何選擇候選者,具體使用方式如下: @Autowired @Qualifier(value
= “demoInfoService”) private DemoInfoService demoInfoService; @Resource(name=”name”,type=”type”):沒有括號內內容的話,默認byName。與@Autowired干類似的事。

3.2 JPA注解

@Entity:@Table(name=”“):表明這是一個實體類。一般用於jpa這兩個注解一般一塊使用,但是如果表名和實體類名相同的話,@Table可以省略

@MappedSuperClass:用在確定是父類的entity上。父類的屬性子類可以繼承。

@NoRepositoryBean:一般用作父類的repository,有這個注解,spring不會去實例化該repository。

@Column:如果字段名與列名相同,則可以省略。

@Id:表示該屬性為主鍵。

@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):
表示主鍵生成策略是sequence(可以為Auto、IDENTITY、native等,Auto表示可在多個數據庫間切換),指定sequence的名字是repair_seq。 @SequenceGeneretor(name
= “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):
name為sequence的名稱,以便使用,sequenceName為數據庫的sequence名稱,兩個名稱可以一致。 @Transient:表示該屬性並非一個到數據庫表的字段的映射,ORM框架將忽略該屬性。如果一個屬性並非數據庫表的字段映射,
就務必將其標示為@Transient,否則,ORM框架默認其注解為@Basic。@Basic(fetch
=FetchType.LAZY):標記可以指定實體屬性的加載方式 @JsonIgnore:作用是json序列化時將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。 @JoinColumn(name=”loginId”):一對一:本表中指向另一個表的外鍵。一對多:另一個表指向本表的外鍵。 @OneToOne、@OneToMany、@ManyToOne:對應hibernate配置文件中的一對一,一對多,多對一。

3.3 springMVC相關注解

@RequestMapping:@RequestMapping(“/path”)表示該控制器處理所有“/path”的UR L請求。RequestMapping是一個用來處理請求地址映射的注解,可用於類或方法上。
用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。

該注解有六個屬性:
params:指定request中必須包含某些參數值是,才讓該方法處理。
headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。
value:指定請求的實際地址,指定的地址可以是URI Template 模式
method:指定請求的method類型, GET、POST、PUT、DELETE等
consumes:指定處理請求的提交內容類型(Content-Type),如application/json,text/html;
produces:指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回

3.4 異常處理注解

@ControllerAdvice:包含@Component。可以被掃描到。統一處理異常。
@ExceptionHandler(Exception.class):用在方法上面表示遇到這個異常就執行以下方法。
用法可參考: https://blog.csdn.net/kinginblue/article/details/70186586

常用的注解沒有很復雜的內容和用法,下面是別人總結的常用注解,可以看一看

springboot 常用注解 https://www.yuque.com/zhangjian-mbxkb/zu7dxg/qgpomk