成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

聊聊Spring中的各項注解

開發 架構
作者個人研發的在高并發場景下,提供的簡單、穩定、可擴展的延遲消息隊列框架,具有精準的定時任務和延遲隊列處理功能。

[[385848]]

作者個人研發的在高并發場景下,提供的簡單、穩定、可擴展的延遲消息隊列框架,具有精準的定時任務和延遲隊列處理功能。自開源半年多以來,已成功為十幾家中小型企業提供了精準定時調度方案,經受住了生產環境的考驗。為使更多童鞋受益,現給出開源框架地址:https://github.com/sunshinelyz/mykit-delay

寫在前面

由于在更新其他專題的文章,Spring系列文章有很長一段時間沒有更新了,很多小伙伴都在公眾號后臺留言或者直接私信我微信催更Spring系列文章。

看來是要繼續更新Spring文章了。想來想去,寫一篇關于Spring中注解相關的文章吧,因為之前更新Spring系列的文章一直也是在更新Spring注解驅動開發。這篇文章也算是對之前文章的一個小小的總結吧,估計更新完這篇,我們會進入Spring的AOP章節的更新。

文章已收錄到:

https://github.com/sunshinelyz/technology-binghe

https://gitee.com/binghe001/technology-binghe

xml配置與類配置

1.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sp 
  5.  <bean id="person" class="com.binghe.spring.Person"></bean> 
  6. </beans> 

獲取Person實例如下所示。

  1. public static void main( String[] args ){ 
  2.  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); 
  3.  System.out.println(ctx.getBean("person")); 

2.類配置

  1. @Configuration 
  2. public class MainConfig { 
  3.     @Bean 
  4.     public Person person(){ 
  5.      return new Person(); 
  6.     } 
  7. }   

這里,有一個需要注意的地方:通過@Bean的形式是使用的話, bean的默認名稱是方法名,若@Bean(value="bean的名稱")那么bean的名稱是指定的 。

獲取Person實例如下所示。

  1. public static void main( String[] args ){ 
  2.  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class); 
  3.  System.out.println(ctx.getBean("person")); 

@CompentScan注解

我們可以使用@CompentScan注解來進行包掃描,如下所示。

  1. @Configuration 
  2. @ComponentScan(basePackages = {"com.binghe.spring"}) 
  3.  public class MainConfig { 
  4. }  

excludeFilters 屬性

當我們使用@CompentScan注解進行掃描時,可以使用@CompentScan注解的excludeFilters 屬性來排除某些類,如下所示。

  1. @Configuration 
  2. @ComponentScan(basePackages = {"com.binghe.spring"},excludeFilters = { 
  3. @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}), 
  4. @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {PersonService.class}) 
  5. }) 
  6. public class MainConfig { 

includeFilters屬性

當我們使用@CompentScan注解進行掃描時,可以使用@CompentScan注解的includeFilters屬性將某些類包含進來。這里需要注意的是:需要把useDefaultFilters屬性設置為false(true表示掃描全部的)

  1. @Configuration 
  2. @ComponentScan(basePackages = {"com.binghe.spring"},includeFilters = { 
  3. @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, PersonService.class}) 
  4. },useDefaultFilters = false
  5. public class MainConfig { 

@ComponentScan.Filter type的類型

注解形式的FilterType.ANNOTATION @Controller @Service @Repository @Compent

  • 指定類型的 FilterType.ASSIGNABLE_TYPE @ComponentScan.Filter(type =FilterType.ASSIGNABLE_TYPE,value = {Person.class})
  • aspectj類型的 FilterType.ASPECTJ(不常用)
  • 正則表達式的 FilterType.REGEX(不常用)
  • 自定義的 FilterType.CUSTOM
  1. public enum FilterType { 
  2.     //注解形式 比如@Controller @Service @Repository @Compent 
  3.     ANNOTATION, 
  4.     //指定的類型 
  5.     ASSIGNABLE_TYPE, 
  6.     //aspectJ形式的 
  7.     ASPECTJ, 
  8.     //正則表達式的 
  9.     REGEX, 
  10.     //自定義的 
  11.     CUSTOM 

FilterType.CUSTOM 自定義類型

  1. public class CustomFilterType implements TypeFilter { 
  2. @Override 
  3. public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { 
  4.     //獲取當前類的注解源信息 
  5.     AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); 
  6.     //獲取當前類的class的源信息 
  7.     ClassMetadata classMetadata = metadataReader.getClassMetadata(); 
  8.     //獲取當前類的資源信息 
  9.     Resource resource = metadataReader.getResource(); 
  10.   return classMetadata.getClassName().contains("Service"); 
  11.      
  12. @ComponentScan(basePackages = {"com.binghe.spring"},includeFilters = { 
  13. @ComponentScan.Filter(type = FilterType.CUSTOM,value = CustomFilterType.class) 
  14. },useDefaultFilters = false
  15. public class MainConfig { 

配置Bean的作用域對象

不指定@Scope

在不指定@Scope的情況下,所有的bean都是單實例的bean,而且是餓漢加載(容器啟動實例就創建好了)

  1. @Bean 
  2. public Person person() { 
  3.  return new Person(); 
  4. }  

@Scope為 prototype

指定@Scope為 prototype 表示為多實例的,而且還是懶漢模式加載(IOC容器啟動的時候,并不會創建對象,而是在第一次使用的時候才會創建)

  1. @Bean 
  2. @Scope(value = "prototype"
  3. public Person person() { 
  4.     return new Person(); 

@Scope取值

  • singleton 單實例的(默認)
  • prototype 多實例的
  • request 同一次請求
  • session 同一個會話級別

懶加載

Bean的懶加載@Lazy(主要針對單實例的bean 容器啟動的時候,不創建對象,在第一次使用的時候才會創建該對象)

  1. @Bean 
  2. @Lazy 
  3. public Person person() { 
  4.  return new Person(); 

@Conditional條件判斷

場景,有二個組件CustomAspect 和CustomLog ,我的CustomLog組件是依賴于CustomAspect的組件 應用:自己創建一個CustomCondition的類 實現Condition接口

  1. public class CustomCondition implements Condition { 
  2. /**** 
  3. @param context 
  4. * @param metadata 
  5. * @return 
  6. */ 
  7.     @Override 
  8.     public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { 
  9.         //判斷容器中是否有CustomAspect的組件 
  10.         return context.getBeanFactory().containsBean("customAspect"); 
  11.     }  
  12. }  
  13.  
  14. public class MainConfig { 
  15.     @Bean 
  16.     public CustomAspect customAspect() { 
  17.         return new CustomAspect(); 
  18.     }  
  19.     @Bean 
  20.     @Conditional(value = CustomCondition.class) 
  21.     public CustomLog customLog() { 
  22.      return new CustomLog(); 
  23.     } 

向IOC 容器添加組件

(1)通過@CompentScan +@Controller @Service @Respository @compent。適用場景: 針對我們自己寫的組件可以通過該方式來進行加載到容器中。

(2)通過@Bean的方式來導入組件(適用于導入第三方組件的類)

(3)通過@Import來導入組件 (導入組件的id為全類名路徑)

  1. @Configuration 
  2. @Import(value = {Person.class}) 
  3. public class MainConfig { 

通過@Import 的ImportSeletor類實現組件的導入 (導入組件的id為全類名路徑)

  1. public class CustomImportSelector implements ImportSelector {  
  2.     @Override 
  3.     public String[] selectImports(AnnotationMetadata importingClassMetadata) { 
  4.      return new String[]{"com.binghe.spring"}; 
  5.     } 
  6. }  
  7. Configuration 
  8. @Import(value = {Person.class} 
  9. public class MainConfig { 

通過@Import的 ImportBeanDefinitionRegister導入組件 (可以指定bean的名稱)

  1. public class DogBeanDefinitionRegister implements ImportBeanDefinitionRegistrar { 
  2.     @Override 
  3.     public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { 
  4.         //創建一個bean定義對象 
  5.         RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Dog.class); 
  6.         //把bean定義對象導入到容器中 
  7.         registry.registerBeanDefinition("dog",rootBeanDefinition); 
  8.     } 
  9. }  
  10. @Configuration 
  11. @Import(value = {Person.class, Car.class, CustomImportSelector.class, DogBeanDefinitionRegister.class}) 
  12. public class MainConfig { 

通過實現FacotryBean接口來實現注冊 組件

  1. public class CarFactoryBean implements FactoryBean<Car> { 
  2.     @Override 
  3.     public Car getObject() throws Exception { 
  4.      return new Car(); 
  5.     }  
  6.     @Override 
  7.     public Class<?> getObjectType() { 
  8.      return Car.class; 
  9.     }  
  10.  
  11.     @Override 
  12.     public boolean isSingleton() { 
  13.      return true
  14.     } 

Bean的初始化與銷毀

指定bean的初始化方法和bean的銷毀方法

由容器管理Bean的生命周期,我們可以通過自己指定bean的初始化方法和bean的銷毀方法

  1. @Configuration 
  2. public class MainConfig { 
  3.     //指定了bean的生命周期的初始化方法和銷毀方法.@Bean(initMethod = "init",destroyMethod = "destroy"
  4.     public Car car() { 
  5.      return new Car(); 
  6.     } 

針對單實例bean的話,容器啟動的時候,bean的對象就創建了,而且容器銷毀的時候,也會調用Bean的銷毀方法

針對多實例bean的話,容器啟動的時候,bean是不會被創建的而是在獲取bean的時候被創建,而且bean的銷毀不受IOC容器的管理

通過 InitializingBean和DisposableBean實現

通過 InitializingBean和DisposableBean個接口實現bean的初始化以及銷毀方法

  1. @Component 
  2. public class Person implements InitializingBean,DisposableBean { 
  3.     public Person() { 
  4.      System.out.println("Person的構造方法"); 
  5.     }  
  6.     @Override 
  7.     public void destroy() throws Exception { 
  8.      System.out.println("DisposableBean的destroy()方法 "); 
  9.     }  
  10.     @Override 
  11.     public void afterPropertiesSet() throws Exception { 
  12.      System.out.println("InitializingBean的 afterPropertiesSet方法"); 
  13.     } 

通過JSR250規范

通過JSR250規范 提供的注解@PostConstruct 和@ProDestory標注的方法

  1. @Component 
  2. public class Book { 
  3.     public Book() { 
  4.      System.out.println("book 的構造方法"); 
  5.     }  
  6.     @PostConstruct 
  7.     public void init() { 
  8.      System.out.println("book 的PostConstruct標志的方法"); 
  9.     }  
  10.     @PreDestroy 
  11.     public void destory() { 
  12.      System.out.println("book 的PreDestory標注的方法"); 
  13.     } 

通過BeanPostProcessor實現

通過Spring的BeanPostProcessor的 bean的后置處理器會攔截所有bean創建過程

  • postProcessBeforeInitialization 在init方法之前調用
  • postProcessAfterInitialization 在init方法之后調用
  1. @Component 
  2. public class CustomBeanPostProcessor implements BeanPostProcessor { 
  3.     @Override 
  4.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 
  5.      System.out.println("CustomBeanPostProcessor...postProcessBeforeInitialization:"+beanName); 
  6.      return bean; 
  7.     }  
  8.     @Override 
  9.     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 
  10.         System.out.println("CustomBeanPostProcessor...postProcessAfterInitialization:"+beanName); 
  11.         return bean; 
  12.     } 
  13. }  

BeanPostProcessor的執行時機

  1. populateBean(beanName, mbd, instanceWrapper) 
  2. initializeBean{ 
  3.     applyBeanPostProcessorsBeforeInitialization() 
  4.     invokeInitMethods{ 
  5.     isInitializingBean.afterPropertiesSet() 
  6.     自定義的init方法 
  7. applyBeanPostProcessorsAfterInitialization()方法 

通過@Value +@PropertySource來給組件賦值

  1. public class Person { 
  2.     //通過普通的方式 
  3.     @Value("獨孤"
  4.     private String firstName; 
  5.     //spel方式來賦值 
  6.     @Value("#{28-8}"
  7.     private Integer age; 
  8.     通過讀取外部配置文件的值 
  9.     @Value("${person.lastName}"
  10.     private String lastName; 
  11. }  
  12. @Configuration 
  13. @PropertySource(value = {"classpath:person.properties"}) //指定外部文件的位置 
  14. public class MainConfig { 
  15.     @Bean 
  16.     public Person person() { 
  17.         return new Person(); 
  18.     } 

自動裝配

@AutoWired的使用

自動注入

  1. @Repository 
  2. public class CustomDao { 
  3. }  
  4. @Service 
  5. public class CustomService { 
  6.     @Autowired 
  7.     private CustomDao customDao; 
  8. } 

結論: (1)自動裝配首先時按照類型進行裝配,若在IOC容器中發現了多個相同類型的組件,那么就按照 屬性名稱來進行裝配

  1. @Autowired 
  2. private CustomDao customDao; 

比如,我容器中有二個CustomDao類型的組件 一個叫CustomDao 一個叫CustomDao2那么我們通過@AutoWired 來修飾的屬性名稱時CustomDao,那么拿就加載容器的CustomDao組件,若屬性名稱為tulignDao2 那么他就加載的時CustomDao2組件

(2)假設我們需要指定特定的組件來進行裝配,我們可以通過使用@Qualifier("CustomDao")來指定裝配的組件 或者在配置類上的@Bean加上@Primary注解

  1. @Autowired 
  2. @Qualifier("CustomDao"
  3. private CustomDao customDao2 

(3)假設我們容器中即沒有CustomDao 和CustomDao2,那么在裝配的時候就會拋出異常

  1. No qualifying bean of type 'com.binghhe.spring.dao.CustomDao' available 

若我們想不拋異常 ,我們需要指定 required為false的時候可以了

  1. @Autowired(required = false
  2. @Qualifier("customDao"
  3. private CustomDao CustomDao2; 

(4)@Resource(JSR250規范) 功能和@AutoWired的功能差不多一樣,但是不支持@Primary 和@Qualifier的支持

(5)@InJect(JSR330規范) 需要導入jar包依賴,功能和支持@Primary功能 ,但是沒有Require=false的功能

  1. <dependency> 
  2.     <groupId>javax.inject</groupId> 
  3.     <artifactId>javax.inject</artifactId> 
  4.     <version>1</version> 
  5. </dependency> 

(6)使用@Autowired 可以標注在方法上

  • 標注在set方法上
  1. //@Autowired 
  2. public void setCustomLog(CustomLog customLog) { 
  3.  this.customLog = customLog; 
  • 標注在構造方法上
  1. @Autowired 
  2. public CustomAspect(CustomLog customLog) { 
  3.  this.customLog = customLog; 

標注在配置類上的入參中(可以不寫)

  1. @Bean 
  2. public CustomAspect CustomAspect(@Autowired CustomLog customLog) { 
  3.     CustomAspect customAspect = new CustomAspect(customLog); 
  4.     return ustomAspect; 

XXXAwarce接口

我們自己的組件 需要使用spring ioc的底層組件的時候,比如 ApplicationContext等我們可以通過實現XXXAware接口來實現

  1. @Component 
  2. public class CustomCompent implements ApplicationContextAware,BeanNameAware { 
  3.     private ApplicationContext applicationContext; 
  4.     @Override 
  5.     public void setBeanName(String name) { 
  6.      System.out.println("current bean name is :【"+name+"】"); 
  7.     }  
  8.     @Override 
  9.     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 
  10.      this.applicationContext = applicationContext; 
  11.     } 

@Profile注解

通過@Profile注解 來根據環境來激活標識不同的Bean

@Profile標識在類上,那么只有當前環境匹配,整個配置類才會生效

@Profile標識在Bean上 ,那么只有當前環境的Bean才會被激活

沒有標志為@Profile的bean 不管在什么環境都可以被激活

  1. @Configuration 
  2. @PropertySource(value = {"classpath:ds.properties"}) 
  3. public class MainConfig implements EmbeddedValueResolverAware { 
  4.     @Value("${ds.username}"
  5.     private String userName; 
  6.     @Value("${ds.password}"
  7.     private String password
  8.     private String jdbcUrl; 
  9.     private String classDriver; 
  10.     @Override 
  11.     public void setEmbeddedValueResolver(StringValueResolver resolver) { 
  12.         this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}"); 
  13.         this.classDriver = resolver.resolveStringValue("${ds.classDriver}"); 
  14.     }  
  15.     @Bean 
  16.     @Profile(value = "test"
  17.     public DataSource testDs() { 
  18.      return buliderDataSource(new DruidDataSource()); 
  19.     } 
  20.     @Bean 
  21.     @Profile(value = "dev"
  22.     public DataSource devDs() { 
  23.      return buliderDataSource(new DruidDataSource()); 
  24.     }  
  25.     @Bean 
  26.     @Profile(value = "prod"
  27.     public DataSource prodDs() { 
  28.      return buliderDataSource(new DruidDataSource()); 
  29.     }  
  30.     private DataSource buliderDataSource(DruidDataSource dataSource) { 
  31.         dataSource.setUsername(userName); 
  32.         dataSource.setPassword(password); 
  33.         dataSource.setDriverClassName(classDriver); 
  34.         dataSource.setUrl(jdbcUrl); 
  35.      return dataSource; 
  36.     } 

激活切換環境的方法

(1)運行時jvm參數來切換

  1. -Dspring.profiles.active=test|dev|prod   

(2)通過代碼的方式來激活

  1. public static void main(String[] args) { 
  2.     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
  3.     ctx.getEnvironment().setActiveProfiles("test","dev"); 
  4.     ctx.register(MainConfig.class); 
  5.     ctx.refresh(); 
  6.     printBeanName(ctx); 

本文轉載自微信公眾號「冰河技術」,可以通過以下二維碼關注。轉載本文請聯系冰河技術公眾號。

 

責任編輯:武曉燕 來源: 冰河技術
相關推薦

2022-03-03 07:34:31

注解容器作用域

2017-12-22 09:59:43

2024-03-04 07:41:18

SpringAOPOOP?

2025-06-09 01:01:00

2022-06-28 14:57:09

FormatterSpring

2021-11-17 08:11:35

MySQL

2022-05-05 10:40:36

Spring權限對象

2022-01-26 00:05:00

接口Spring管理器

2023-04-28 08:43:46

2021-06-04 08:48:46

Spring ClouMaven Centr版本

2020-07-02 07:44:27

Spring教程異步

2025-05-09 09:05:00

Spring框架設計模式

2023-11-09 11:56:28

MySQL死鎖

2021-08-31 07:54:24

SQLDblink查詢

2024-04-26 00:00:00

Rust檢查器代碼

2024-10-23 08:13:30

Spring響應式編程

2024-11-14 14:53:04

2021-10-30 19:56:10

Flutter按鈕 Buttons

2022-05-11 09:01:54

Swift類型系統幻象類型

2023-07-28 09:54:14

SQL數據Excel
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 中文字幕视频在线 | 天堂色综合 | 国产黄色在线观看 | 黑人成人网 | 九九免费观看视频 | 黄片毛片免费看 | 亚洲精品第一国产综合野 | 91看片网 | 亚洲精品在线观 | 在线免费av电影 | 亚洲精品久久久蜜桃 | 欧美一区二区三区在线观看视频 | 国内在线视频 | 欧美精品一区二区三区四区 在线 | 成人a视频在线观看 | 午夜影院在线观看免费 | 欧美成人精品一区二区男人看 | 涩涩视频在线观看 | 精品无码久久久久久国产 | 一级毛片中国 | 国产精品国产成人国产三级 | 亚洲综合中文字幕在线观看 | 久久青 | 久久九九免费 | 少妇午夜一级艳片欧美精品 | 久综合| 成人亚洲精品 | 午夜在线观看免费 | 亚洲福利av| 国产精品99久久久久久www | 日韩免费网 | 国产成人一区二区 | www久| 日韩色视频 | 最新超碰 | 中国一级特黄视频 | 午夜精品一区二区三区在线视频 | 精品一区二区久久久久久久网站 | 精品视频网 | 亚洲狠狠爱 | 精品人伦一区二区三区蜜桃网站 |