溫馨提示×

溫馨提示×

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

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

Springboot如何實現(xiàn)自動裝配

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

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

創(chuàng)建一個簡單的項目:

<&#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>

首先創(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 作用于類上,表示這是一個組件,于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如何實現(xiàn)自動裝配

import注解引入配置文件。

編寫測試類測試:

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

  @Autowired
  public MyConsumer myConsumer;

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

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

向AI問一下細節(jié)

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

AI