日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
IOC容器注解匯總,你想要的都在這兒了?。?/div>

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

專注于為中小企業(yè)提供網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)東鄉(xiāng)免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了上1000+企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。

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

xml配置與類配置

1.xml配置

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

 
 
 
 
  1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sp
  3.  

2.類配置

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

這里,有一個需要注意的地方:通過@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"));
  4. }

@CompentScan注解

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

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

excludeFilters 屬性

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

includeFilters屬性

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

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

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.     
  13. @ComponentScan(basePackages = {"com.binghe.spring"},includeFilters = {
  14. @ComponentScan.Filter(type = FilterType.CUSTOM,value = CustomFilterType.class)
  15. },useDefaultFilters = false)
  16. public class MainConfig {
  17. }

配置Bean的作用域?qū)ο?/strong>

不指定@Scope

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

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

@Scope為 prototype

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

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

@Scope取值

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

懶加載

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

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

@Conditional條件判斷

場景,有二個組件CustomAspect 和CustomLog ,我的CustomLog組件是依賴于CustomAspect的組件 應(yīng)用:自己創(chuàng)建一個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. public class MainConfig {
  13.     @Bean
  14.     public CustomAspect customAspect() {
  15.         return new CustomAspect();
  16.     } 
  17.     @Bean
  18.     @Conditional(value = CustomCondition.class)
  19.     public CustomLog customLog() {
  20.      return new CustomLog();
  21.     }
  22. }

向IOC 容器添加組件

(1)通過@CompentScan +@Controller @Service @Respository @compent。適用場景: 針對我們自己寫的組件可以通過該方式來進(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 {
  4. }

通過@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. Configuration
  7. @Import(value = {Person.class}
  8. public class MainConfig {
  9. }

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

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

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

 
 
 
 
  1. public class CarFactoryBean implements FactoryBean {
  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.     @Override
  11.     public boolean isSingleton() {
  12.      return true;
  13.     }
  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.     }
  7. }

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

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

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

通過 InitializingBean和DisposableBean個接口實(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.     }
  14. }

通過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.     }
  14. }

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

通過Spring的BeanPostProcessor的 bean的后置處理器會攔截所有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.     }

BeanPostProcessor的執(zhí)行時機(jī)

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

通過@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. @Configuration
  12. @PropertySource(value = {"classpath:person.properties"}) //指定外部文件的位置
  13. public class MainConfig {
  14.     @Bean
  15.     public Person person() {
  16.         return new Person();
  17.     }
  18. }

自動裝配

@AutoWired的使用

自動注入

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

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

 
 
 
 
  1. @Autowired
  2. private CustomDao customDao;

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

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

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

(3)假設(shè)我們?nèi)萜髦屑礇]有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規(guī)范) 功能和@AutoWired的功能差不多一樣,但是不支持@Primary 和@Qualifier的支持

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

 
 
 
 
  1.     javax.inject
  2.     javax.inject
  3.     1

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

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

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

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

XXXAwarce接口

我們自己的組件 需要使用spring ioc的底層組件的時候,比如 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.     }
  12. }

@Profile注解

通過@Profile注解 來根據(jù)環(huán)境來激活標(biāo)識不同的Bean

  • @Profile標(biāo)識在類上,那么只有當(dāng)前環(huán)境匹配,整個配置類才會生效
  • @Profile標(biāo)識在Bean上 ,那么只有當(dāng)前環(huán)境的Bean才會被激活
  • 沒有標(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.     }
  37. }

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

(1)運(yùn)行時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);
  7. }

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


本文標(biāo)題:IOC容器注解匯總,你想要的都在這兒了?。?
URL地址:http://www.5511xx.com/article/cdhcojg.html