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

IOC容器注解匯總,你想要的都在這兒了!!

開發(fā) 前端
作者個(gè)人研發(fā)的在高并發(fā)場景下,提供的簡單、穩(wěn)定、可擴(kuò)展的延遲消息隊(duì)列框架,具有精準(zhǔn)的定時(shí)任務(wù)和延遲隊(duì)列處理功能。

 [[341332]]

作者個(gè)人研發(fā)的在高并發(fā)場景下,提供的簡單、穩(wěn)定、可擴(kuò)展的延遲消息隊(duì)列框架,具有精準(zhǔn)的定時(shí)任務(wù)和延遲隊(duì)列處理功能。自開源半年多以來,已成功為十幾家中小型企業(yè)提供了精準(zhǔn)定時(shí)調(diào)度方案,經(jīng)受住了生產(chǎn)環(huán)境的考驗(yàn)。為使更多童鞋受益,現(xiàn)給出開源框架地址:

https://github.com/sunshinelyz/mykit-delay

xml配置與類配置

1.xml配置

獲取Person實(shí)例如下所示。

  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> 

2.類配置

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

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

獲取Person實(shí)例如下所示。

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

@CompentScan注解

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

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

excludeFilters 屬性

當(dāng)我們使用@CompentScan注解進(jìn)行掃描時(shí),可以使用@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屬性

當(dāng)我們使用@CompentScan注解進(jìn)行掃描時(shí),可以使用@CompentScan注解的includeFilters屬性將某些類包含進(jìn)來。這里需要注意的是:需要把useDefaultFilters屬性設(shè)置為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(不常用)
  • 正則表達(dá)式的 FilterType.REGEX(不常用)
  • 自定義的 FilterType.CUSTOM
  1. public enum FilterType { 
  2.     //注解形式 比如@Controller @Service @Repository @Compent 
  3.     ANNOTATION, 
  4.     //指定的類型 
  5.     ASSIGNABLE_TYPE, 
  6.     //aspectJ形式的 
  7.     ASPECTJ, 
  8.     //正則表達(dá)式的 
  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.     //獲取當(dāng)前類的注解源信息 
  5.     AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); 
  6.     //獲取當(dāng)前類的class的源信息 
  7.     ClassMetadata classMetadata = metadataReader.getClassMetadata(); 
  8.     //獲取當(dāng)前類的資源信息 
  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的作用域?qū)ο?/strong>

不指定@Scope

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

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

@Scope為 prototype

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

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

@Scope取值

  • singleton 單實(shí)例的(默認(rèn))
  • prototype 多實(shí)例的
  • request 同一次請(qǐng)求
  • session 同一個(gè)會(huì)話級(jí)別

懶加載

Bean的懶加載@Lazy(主要針對(duì)單實(shí)例的bean 容器啟動(dòng)的時(shí)候,不創(chuàng)建對(duì)象,在第一次使用的時(shí)候才會(huì)創(chuàng)建該對(duì)象)

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

@Conditional條件判斷

場景,有二個(gè)組件CustomAspect 和CustomLog ,我的CustomLog組件是依賴于CustomAspect的組件 應(yīng)用:自己創(chuàng)建一個(gè)CustomCondition的類 實(shí)現(xiàn)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。適用場景: 針對(duì)我們自己寫的組件可以通過該方式來進(jìn)行加載到容器中。

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

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

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

通過@Import 的ImportSeletor類實(shí)現(xiàn)組件的導(dǎo)入 (導(dǎo)入組件的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導(dǎo)入組件 (可以指定bean的名稱)

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

通過實(shí)現(xiàn)FacotryBean接口來實(shí)現(xiàn)注冊(cè) 組件

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

針對(duì)單實(shí)例bean的話,容器啟動(dòng)的時(shí)候,bean的對(duì)象就創(chuàng)建了,而且容器銷毀的時(shí)候,也會(huì)調(diào)用Bean的銷毀方法

針對(duì)多實(shí)例bean的話,容器啟動(dòng)的時(shí)候,bean是不會(huì)被創(chuàng)建的而是在獲取bean的時(shí)候被創(chuàng)建,而且bean的銷毀不受IOC容器的管理

通過 InitializingBean和DisposableBean實(shí)現(xiàn)

通過 InitializingBean和DisposableBean個(gè)接口實(shí)現(xiàn)bean的初始化以及銷毀方法

  1. @Component 
  2. public class Person implements InitializingBean,DisposableBean { 
  3.     public Person() { 
  4.      System.out.println("Person的構(gòu)造方法"); 
  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規(guī)范

通過JSR250規(guī)范 提供的注解@PostConstruct 和@ProDestory標(biāo)注的方法

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

通過BeanPostProcessor實(shí)現(xiàn)

通過Spring的BeanPostProcessor的 bean的后置處理器會(huì)攔截所有bean創(chuàng)建過程

  • postProcessBeforeInitialization 在init方法之前調(diào)用
  • postProcessAfterInitialization 在init方法之后調(diào)用
  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的執(zhí)行時(shí)機(jī)

  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("獨(dú)孤"
  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.     } 

自動(dòng)裝配

@AutoWired的使用

自動(dòng)注入

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

結(jié)論: (1)自動(dòng)裝配首先時(shí)按照類型進(jìn)行裝配,若在IOC容器中發(fā)現(xiàn)了多個(gè)相同類型的組件,那么就按照 屬性名稱來進(jìn)行裝配

  1. @Autowired 
  2. private CustomDao customDao; 

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

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

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

(3)假設(shè)我們?nèi)萜髦屑礇]有CustomDao 和CustomDao2,那么在裝配的時(shí)候就會(huì)拋出異常

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

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

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

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

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

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

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

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

標(biāo)注在配置類上的入?yún)⒅?可以不寫)

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

XXXAwarce接口

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

  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注解 來根據(jù)環(huán)境來激活標(biāo)識(shí)不同的Bean

  • @Profile標(biāo)識(shí)在類上,那么只有當(dāng)前環(huán)境匹配,整個(gè)配置類才會(huì)生效
  • @Profile標(biāo)識(shí)在Bean上 ,那么只有當(dāng)前環(huán)境的Bean才會(huì)被激活
  • 沒有標(biāo)志為@Profile的bean 不管在什么環(huán)境都可以被激活
  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.     } 

激活切換環(huán)境的方法

(1)運(yùn)行時(shí)jvm參數(shù)來切換

  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); 

本文轉(zhuǎn)載自微信公眾號(hào)「冰河技術(shù)」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系冰河技術(shù)公眾號(hào)。

 

責(zé)任編輯:武曉燕 來源: 冰河技術(shù)
相關(guān)推薦

2018-06-26 04:49:46

運(yùn)營商流量漫游提速降費(fèi)

2019-04-19 08:25:13

HBase基礎(chǔ)Google

2019-04-22 14:12:12

HBase集群Google

2025-05-16 09:34:10

2016-10-18 08:58:14

Linux瀏覽器電子郵件

2019-10-29 15:28:40

Refs組件前端

2022-09-15 14:22:19

協(xié)作規(guī)范前后端

2019-12-04 07:57:22

6G5G網(wǎng)絡(luò)

2019-01-24 08:19:17

云服務(wù)多云云計(jì)算

2021-07-06 05:23:05

軟件限免游戲Steam

2018-11-28 10:39:01

5G網(wǎng)絡(luò)運(yùn)營商

2018-03-31 08:45:52

iPhone交通卡iOS 11.3

2018-08-07 15:18:01

2017-08-25 12:06:36

Facebook

2020-07-24 10:04:12

5G網(wǎng)絡(luò)技術(shù)

2013-05-27 09:33:13

Windows 8.1

2017-01-11 08:37:07

Apache SparStreamingDataFrames

2021-07-02 14:09:36

開發(fā)技能代碼

2021-11-01 08:00:00

Java異常處理開發(fā)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 国产精品视频久久久久 | 欧美精品a∨在线观看不卡 国产精品久久国产精品 | 古装三级在线播放 | 午夜爱爱网 | 欧美在线激情 | 亚洲第一色站 | 亚洲午夜网 | 日韩成人在线网址 | 九九精品久久久 | 美国一级片在线观看 | 在线视频一区二区三区 | 欧美区在线 | 成人综合久久 | 国产乱性 | 久久精品国产一区二区三区不卡 | 欧美色综合 | 亚洲乱码一区二区三区在线观看 | 婷婷综合五月天 | 国产精品呻吟久久av凹凸 | 久久精品色欧美aⅴ一区二区 | 久久五月婷 | 日本在线视频一区二区 | 欧美色综合一区二区三区 | 日韩精品一区二区三区老鸭窝 | 亚洲电影免费 | 99久久久99久久国产片鸭王 | www在线视频 | 精品国产青草久久久久福利 | 国产欧美精品区一区二区三区 | 一区二区国产精品 | 欧美亚洲激情 | 日韩欧美中文字幕在线观看 | 最新中文字幕第一页视频 | 免费观看av| 国产精品久久久亚洲 | 国产高清视频一区二区 | 精品一区二区三区在线视频 | a久久 | 午夜不卡一区二区 | 伊人电影院av | 国产视频二区在线观看 |