欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot自動(dòng)裝配實(shí)現(xiàn)過(guò)程代碼實(shí)例

 更新時(shí)間:2020年06月11日 09:41:34   作者:Zs夏至  
這篇文章主要介紹了Springboot自動(dòng)裝配實(shí)現(xiàn)過(guò)程代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

創(chuàng)建一個(gè)簡(jiǎn)單的項(xiàng)目:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.1.12.RELEASE</version>
  </parent>

  <groupId>com.xiazhi</groupId>
  <artifactId>demo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
  </dependencies>
</project>

首先創(chuàng)建自定義注解:

package com.xiazhi.demo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * MyComponent 作用于類上,表示這是一個(gè)組件,于component,service注解作用相同
 * @author zhaoshuai
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyComponent {

}
package com.xiazhi.demo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 作用于字段上,自動(dòng)裝配的注解,與autowired注解作用相同
 * @author zhaoshuai
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Reference {
}

然后寫配置類:

package com.xiazhi.demo.config;

import com.xiazhi.demo.annotation.MyComponent;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;


/**
 * @author ZhaoShuai
 * @company lihfinance.com
 * @date Create in 2020/3/21
 **/
public class ComponentAutoConfiguration implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

  private ResourceLoader resourceLoader;

  @Override
  public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
    String className = annotationMetadata.getClassName();
    String basePackages = className.substring(0, className.lastIndexOf("."));

    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry, false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(MyComponent.class));
    scanner.scan(basePackages);
    scanner.setResourceLoader(resourceLoader);
  }

  @Override
  public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
  }

}

上面是配置掃描指定包下被MyComponent注解標(biāo)注的類并注冊(cè)為spring的bean,bean注冊(cè)成功后,下面就是屬性的注入了

package com.xiazhi.demo.config;

import com.xiazhi.demo.annotation.MyComponent;
import com.xiazhi.demo.annotation.Reference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @author ZhaoShuai
 * @company lihfinance.com
 * @date Create in 2020/3/21
 **/
@SpringBootConfiguration
public class Configuration implements ApplicationContextAware {
  private ApplicationContext applicationContext;

  @Bean
  public BeanPostProcessor beanPostProcessor() {
    return new BeanPostProcessor() {

      /**
       * @company lihfinance.com
       * @author create by ZhaoShuai in 2020/3/21
       * 在bean注冊(cè)前會(huì)被調(diào)用
       * @param [bean, beanName]
       * @return java.lang.Object
       **/
      @Override
      public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
      }

      /**
       * @company lihfinance.com
       * @author create by ZhaoShuai in 2020/3/21
       * 在bean注冊(cè)后會(huì)被加載,本次在bean注冊(cè)成功后注入屬性值
       * @param [bean, beanName]
       * @return java.lang.Object
       **/
      @Override
      public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        if (!clazz.isAnnotationPresent(MyComponent.class)) {
          return bean;
        }

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
          if (!field.isAnnotationPresent(Reference.class)) {
            continue;
          }
          Class<?> type = field.getType();
          Object obj = applicationContext.getBean(type);
          ReflectionUtils.makeAccessible(field);
          ReflectionUtils.setField(field, bean, obj);
        }
        return bean;
      }
    };
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}

下面開(kāi)始使用注解來(lái)看看效果:

package com.xiazhi.demo.service;

import com.xiazhi.demo.annotation.MyComponent;

import javax.annotation.PostConstruct;

/**
 * @author ZhaoShuai
 * @company lihfinance.com
 * @date Create in 2020/3/21
 **/
@MyComponent
public class MyService {

  @PostConstruct
  public void init() {
    System.out.println("hello world");
  }

  public void test() {
    System.out.println("測(cè)試案例");
  }
}
package com.xiazhi.demo.service;

import com.xiazhi.demo.annotation.MyComponent;
import com.xiazhi.demo.annotation.Reference;

/**
 * @author ZhaoShuai
 * @company lihfinance.com
 * @date Create in 2020/3/21
 **/
@MyComponent
public class MyConsumer {

  @Reference
  private MyService myService;

  public void aaa() {
    myService.test();
  }
}

啟動(dòng)類要引入配置文件:

import注解引入配置文件。

編寫測(cè)試類測(cè)試:

@SpringBootTest(classes = ApplicationRun.class)
@RunWith(SpringRunner.class)
public class TestDemo {

  @Autowired
  public MyConsumer myConsumer;

  @Test
  public void fun1() {
    myConsumer.aaa();
  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解Java8?StreamAPI中的map()方法

    詳解Java8?StreamAPI中的map()方法

    Stream?API?是Java8中新加入的功能,這篇文章主要帶大家了解一下?Stream?API?中的?map()?方法的使用,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-04-04
  • Java設(shè)計(jì)模式之監(jiān)聽(tīng)器模式實(shí)例詳解

    Java設(shè)計(jì)模式之監(jiān)聽(tīng)器模式實(shí)例詳解

    這篇文章主要介紹了Java設(shè)計(jì)模式之監(jiān)聽(tīng)器模式,結(jié)合實(shí)例形式較為詳細(xì)的分析了java設(shè)計(jì)模式中監(jiān)聽(tīng)器模式的概念、原理及相關(guān)實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下
    2018-02-02
  • java處理按鈕點(diǎn)擊事件的方法

    java處理按鈕點(diǎn)擊事件的方法

    下面小編就為大家?guī)?lái)一篇java處理按鈕點(diǎn)擊事件的方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-04-04
  • Java如何使用poi導(dǎo)入導(dǎo)出excel工具類

    Java如何使用poi導(dǎo)入導(dǎo)出excel工具類

    這篇文章主要介紹了Java如何使用poi導(dǎo)入導(dǎo)出excel工具類問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 一篇文章帶你了解java接口與繼承

    一篇文章帶你了解java接口與繼承

    這篇文章主要介紹了Java接口和繼承操作,結(jié)合具體實(shí)例形式分析了Java接口和繼承與使用的相關(guān)原理、操作技巧與注意事項(xiàng),需要的朋友可以參考下
    2021-08-08
  • SpringCloud高可用配置中心Config詳解

    SpringCloud高可用配置中心Config詳解

    Spring Cloud Config 是一個(gè)解決分布式系統(tǒng)的配置管理方案,它包含了 server 和 client 兩個(gè)部分,這篇文章主要介紹了SpringCloud之配置中心Config(高可用),需要的朋友可以參考下
    2022-04-04
  • IntelliJ安裝并使用Rust IDE插件

    IntelliJ安裝并使用Rust IDE插件

    這篇文章主要介紹了IntelliJ安裝并使用Rust IDE插件,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • java  基礎(chǔ)知識(shí)之IO總結(jié)

    java 基礎(chǔ)知識(shí)之IO總結(jié)

    這篇文章主要介紹了java 基礎(chǔ)知識(shí)之IO總結(jié)的相關(guān)資料,Java中的I/O分為兩種類型,一種是順序讀取,一種是隨機(jī)讀取,需要的朋友可以參考下
    2017-03-03
  • SWT(JFace)體驗(yàn)之Slider,Scale

    SWT(JFace)體驗(yàn)之Slider,Scale

    SWT(JFace)體驗(yàn)之Slider,Scale實(shí)現(xiàn)代碼。
    2009-06-06
  • Java經(jīng)典排序算法之快速排序代碼實(shí)例

    Java經(jīng)典排序算法之快速排序代碼實(shí)例

    這篇文章主要介紹了Java經(jīng)典排序算法之快速排序代碼實(shí)例,快速排序?qū)崿F(xiàn)的思想是指通過(guò)一趟排序?qū)⒁判虻臄?shù)據(jù)分割成獨(dú)立的兩部分,其中一部分的所有數(shù)據(jù)都比另外一部分的所有數(shù)據(jù)都要小,然后再按此方法對(duì)這兩部分?jǐn)?shù)據(jù)分別進(jìn)行快速排序,需要的朋友可以參考下
    2023-10-10

最新評(píng)論