中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Springboot如何實現自動裝配

發布時間:2020-07-17 10:18:13 來源:億速云 閱讀:280 作者:小豬 欄目:編程語言

這篇文章主要為大家展示了Springboot如何實現自動裝配,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。

創建一個簡單的項目:

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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>

首先創建自定義注解:

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 作用于類上,表示這是一個組件,于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;

/**
 * 作用于字段上,自動裝配的注解,與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注解標注的類并注冊為spring的bean,bean注冊成功后,下面就是屬性的注入了

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注冊前會被調用
       * @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注冊后會被加載,本次在bean注冊成功后注入屬性值
       * @param [bean, beanName]
       * @return java.lang.Object
       **/
      @Override
      public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<&#63;> 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<&#63;> 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;
  }
}

下面開始使用注解來看看效果:

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("測試案例");
  }
}
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();
  }
}

啟動類要引入配置文件:

Springboot如何實現自動裝配

import注解引入配置文件。

編寫測試類測試:

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

  @Autowired
  public MyConsumer myConsumer;

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

以上就是關于Springboot如何實現自動裝配的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

侯马市| 慈利县| 马龙县| 眉山市| 郧西县| 兴国县| 长岭县| 新巴尔虎左旗| 永新县| 吉安市| 屏东县| 丹寨县| 运城市| 巩留县| 静安区| 彝良县| 黔东| 武川县| 宜城市| 堆龙德庆县| 太和县| 青神县| 兴安县| 泸州市| 咸丰县| 社旗县| 丹阳市| 林口县| 武清区| 会泽县| 庆云县| 卓资县| 高陵县| 扬中市| 涿鹿县| 师宗县| 吴江市| 察隅县| 象山县| 陕西省| 承德市|