自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

玩轉(zhuǎn)SpringBoot—自動(dòng)裝配解決Bean的復(fù)雜配置

開(kāi)發(fā) 架構(gòu)
ComponentScan的功能其實(shí)就是自動(dòng)掃描并加載符合條件的組件(比如@Component和@Repository等)或者bean定義;并將這些bean定義加載到IoC容器中。

學(xué)習(xí)目標(biāo)

  • 理解自動(dòng)裝配的核心原理
  • 能手寫(xiě)一個(gè)EnableAutoConfiguration注解
  • 理解SPI機(jī)制的原理

第1章 集成Redis

1、引入依賴包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、配置參數(shù)

spring.redis.host=192.168.8.74
spring.redis.password=123456
spring.redis.database=0

3、controller

package com.example.springbootvipjtdemo.redisdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Eclipse_2019
 * @create 2022/6/9 14:36
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/save")
    public String save(@RequestParam String key,@RequestParam String value){
        redisTemplate.opsForValue().set(key,value);
        return "添加成功";
    }

    @GetMapping("/get")
    public String get(@RequestParam String key){
        String value = (String)redisTemplate.opsForValue().get(key);
        return value;
    }
}

通過(guò)上面的案例,我們就能看出來(lái),RedisTemplate這個(gè)類(lèi)的bean對(duì)象,我們并沒(méi)有通過(guò)XML的方式也沒(méi)有通過(guò)注解的方式注入到IoC容器中去,但是我們就是可以通過(guò)@Autowired注解自動(dòng)從容器里面拿到相應(yīng)的Bean對(duì)象,再去進(jìn)行屬性注入。

那這是怎么做到的呢?接下來(lái)我們來(lái)分析一下自動(dòng)裝配的原理,等我們弄明白了原理,自然而然你們就懂了RedisTemplate的bean對(duì)象怎么來(lái)的。

第2章 自動(dòng)裝配原理

1、SpringBootApplication注解是入口

@Target(ElementType.TYPE) // 注解的適用范圍,其中TYPE用于描述類(lèi)、接口(包括包注解類(lèi)型)或enum聲明
@Retention(RetentionPolicy.RUNTIME) // 注解的生命周期,保留到class文件中(三個(gè)生命周期)
@Documented // 表明這個(gè)注解應(yīng)該被javadoc記錄
@Inherited // 子類(lèi)可以繼承該注解
@SpringBootConfiguration // 繼承了Configuration,表示當(dāng)前是注解類(lèi)
@EnableAutoConfiguration // 開(kāi)啟springboot的注解功能,springboot的四大神器之一,其借助@import的幫助
@ComponentScan(excludeFilters = { // 掃描路徑設(shè)置
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
...
}

在其中比較重要的有三個(gè)注解,分別是:

  • @SpringBootConfiguration:繼承了Configuration,表示當(dāng)前是注解類(lèi)。
  • @EnableAutoConfiguration: 開(kāi)啟springboot的注解功能,springboot的四大神器之一,其借助@import的幫助。
  • @ComponentScan(excludeFilters = { // 掃描路徑設(shè)置(具體使用待確認(rèn))。

(1)ComponentScan

ComponentScan的功能其實(shí)就是自動(dòng)掃描并加載符合條件的組件(比如@Component和@Repository等)或者bean定義;并將這些bean定義加載到IoC容器中。

我們可以通過(guò)basePackages等屬性來(lái)細(xì)粒度的定制@ComponentScan自動(dòng)掃描的范圍,如果不指定,則默認(rèn)Spring框架實(shí)現(xiàn)會(huì)從聲明@ComponentScan所在類(lèi)的package進(jìn)行掃描。

注:所以SpringBoot的啟動(dòng)類(lèi)最好是放在root package下,因?yàn)槟J(rèn)不指定basePackages。

(2)EnableAutoConfiguration

此注解顧名思義是可以自動(dòng)配置,所以應(yīng)該是springboot中最為重要的注解。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)//【重點(diǎn)注解】
public @interface EnableAutoConfiguration {
...
}

其中最重要的兩個(gè)注解:

  • @AutoConfigurationPackage
  • @Import(AutoConfigurationImportSelector.class)

當(dāng)然還有其中比較重要的一個(gè)類(lèi)就是:AutoConfigurationImportSelector.class。

AutoConfigurationPackage

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

通過(guò)@Import(AutoConfigurationPackages.Registrar.class)

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {

@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
register(registry, new PackageImport(metadata).getPackageName());
}

……

}

注冊(cè)當(dāng)前啟動(dòng)類(lèi)的根package;注冊(cè)org.springframework.boot.autoconfigure.AutoConfigurationPackages的BeanDefinition。

AutoConfigurationPackage注解的作用是將添加該注解的類(lèi)所在的package作為自動(dòng)配置package 進(jìn)行管理。

可以通過(guò) AutoConfigurationPackages 工具類(lèi)獲取自動(dòng)配置package列表。當(dāng)通過(guò)注解@SpringBootApplication標(biāo)注啟動(dòng)類(lèi)時(shí),已經(jīng)為啟動(dòng)類(lèi)添加了@AutoConfigurationPackage注解。路徑為 @SpringBootApplication -> @EnableAutoConfiguration -> @AutoConfigurationPackage。也就是說(shuō)當(dāng)SpringBoot應(yīng)用啟動(dòng)時(shí)默認(rèn)會(huì)將啟動(dòng)類(lèi)所在的package作為自動(dòng)配置的package。

如我們創(chuàng)建了一個(gè)sbia-demo的應(yīng)用,下面包含一個(gè)啟動(dòng)模塊demo-bootstrap,啟動(dòng)類(lèi)時(shí)Bootstrap,它添加了@SpringBootApplication注解,我們通過(guò)測(cè)試用例可以看到自動(dòng)配置package為com.tm.sbia.demo.boot。

AutoConfigurationImportSelector

可以從圖中看出AutoConfigurationImportSelector實(shí)現(xiàn)了 DeferredImportSelector 從 ImportSelector繼承的方法:selectImports。

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    }
    AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
        .loadMetadata(this.beanClassLoader);
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
    List<String> configurations = getCandidateConfigurations(annotationMetadata,
                                                             attributes);
    configurations = removeDuplicates(configurations);
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    checkExcludedClasses(configurations, exclusions);
    configurations.removeAll(exclusions);
    configurations = filter(configurations, autoConfigurationMetadata);
    fireAutoConfigurationImportEvents(configurations, exclusions);
    return StringUtils.toStringArray(configurations);
}

第9行List configurations =getCandidateConfigurations(annotationMetadata,`attributes);其實(shí)是去加載各個(gè)組件jar下的 public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";外部文件。

如果獲取到類(lèi)信息,spring可以通過(guò)類(lèi)加載器將類(lèi)加載到j(luò)vm中,現(xiàn)在我們已經(jīng)通過(guò)spring-boot的starter依賴方式依賴了我們需要的組件,那么這些組件的類(lèi)信息在select方法中就可以被獲取到。

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
	List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
	Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
 	return configurations;
 }

其返回一個(gè)自動(dòng)配置類(lèi)的類(lèi)名列表,方法調(diào)用了loadFactoryNames方法,查看該方法。

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
	String factoryClassName = factoryClass.getName();
	return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

自動(dòng)配置器會(huì)跟根據(jù)傳入的factoryClass.getName()到項(xiàng)目系統(tǒng)路徑下所有的spring.factories文件中找到相應(yīng)的key,從而加載里面的類(lèi)。

這個(gè)外部文件,有很多自動(dòng)配置的類(lèi)。如下:

其中,最關(guān)鍵的要屬@Import(AutoConfigurationImportSelector.class),借助AutoConfigurationImportSelector,@EnableAutoConfiguration可以幫助SpringBoot應(yīng)用將所有符合條件(spring.factories)的bean定義(如Java Config@Configuration配置)都加載到當(dāng)前SpringBoot創(chuàng)建并使用的IoC容器。

(3)SpringFactoriesLoader

其實(shí)SpringFactoriesLoader的底層原理就是借鑒于JDK的SPI機(jī)制,所以,在將SpringFactoriesLoader之前,我們現(xiàn)在發(fā)散一下SPI機(jī)制。

SPI

SPI ,全稱為 Service Provider Interface,是一種服務(wù)發(fā)現(xiàn)機(jī)制。它通過(guò)在ClassPath路徑下的META-INF/services文件夾查找文件,自動(dòng)加載文件里所定義的類(lèi)。這一機(jī)制為很多框架擴(kuò)展提供了可能,比如在Dubbo、JDBC中都使用到了SPI機(jī)制。我們先通過(guò)一個(gè)很簡(jiǎn)單的例子來(lái)看下它是怎么用的。

例子

首先,我們需要定義一個(gè)接口,SPIService。

package com.example.springbootvipjtdemo.spidemo;

/**
 * @author Eclipse_2019
 * @create 2022/6/8 17:55
 */
public interface SPIService {
    void doSomething();
}

然后,定義兩個(gè)實(shí)現(xiàn)類(lèi),沒(méi)別的意思,只輸入一句話。

package com.example.springbootvipjtdemo.spidemo;

/**
 * @author Eclipse_2019
 * @create 2022/6/8 17:56
 */
public class SpiImpl1 implements SPIService{
    @Override
    public void doSomething() {
        System.out.println("第一個(gè)實(shí)現(xiàn)類(lèi)干活。。。");
    }
}
----------------------我是乖巧的分割線----------------------
package com.example.springbootvipjtdemo.spidemo;

/**
 * @author Eclipse_2019
 * @create 2022/6/8 17:56
 */
public class SpiImpl2 implements SPIService{
    @Override
    public void doSomething() {
        System.out.println("第二個(gè)實(shí)現(xiàn)類(lèi)干活。。。");
    }
}

最后呢,要在ClassPath路徑下配置添加一個(gè)文件。文件名字是接口的全限定類(lèi)名,內(nèi)容是實(shí)現(xiàn)類(lèi)的全限定類(lèi)名,多個(gè)實(shí)現(xiàn)類(lèi)用換行符分隔。
文件路徑如下:

內(nèi)容就是實(shí)現(xiàn)類(lèi)的全限定類(lèi)名:

com.example.springbootvipjtdemo.spidemo.SpiImpl1
com.example.springbootvipjtdemo.spidemo.SpiImpl2

測(cè)試

然后我們就可以通過(guò)ServiceLoader.load或者Service.providers方法拿到實(shí)現(xiàn)類(lèi)的實(shí)例。其中,Service.providers包位于sun.misc.Service,而ServiceLoader.load包位于java.util.ServiceLoader。

public class TestSPI {
    public static void main(String[] args) {
        Iterator<SPIService> providers = Service.providers(SPIService.class);
        ServiceLoader<SPIService> load = ServiceLoader.load(SPIService.class);

        while(providers.hasNext()) {
            SPIService ser = providers.next();
            ser.doSomething();
        }
        System.out.println("--------------------------------");
        Iterator<SPIService> iterator = load.iterator();
        while(iterator.hasNext()) {
            SPIService ser = iterator.next();
            ser.doSomething();
        }
    }
}

兩種方式的輸出結(jié)果是一致的:

第一個(gè)實(shí)現(xiàn)類(lèi)干活。。。
第二個(gè)實(shí)現(xiàn)類(lèi)干活。。。
--------------------------------
第一個(gè)實(shí)現(xiàn)類(lèi)干活。。。
第二個(gè)實(shí)現(xiàn)類(lèi)干活。。。

源碼分析

我們看到一個(gè)位于sun.misc包,一個(gè)位于java.util包,sun包下的源碼看不到。我們就以ServiceLoader.load為例,通過(guò)源碼看看它里面到底怎么做的。

ServiceLoader

首先,我們先來(lái)了解下ServiceLoader,看看它的類(lèi)結(jié)構(gòu)。

public final class ServiceLoader<S> implements Iterable<S>
//配置文件的路徑
private static final String PREFIX = "META-INF/services/";
//加載的服務(wù)類(lèi)或接口
private final Class<S> service;
//已加載的服務(wù)類(lèi)集合
private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
//類(lèi)加載器
private final ClassLoader loader;
//內(nèi)部類(lèi),真正加載服務(wù)類(lèi)
private LazyIterator lookupIterator;
}

Load

load方法創(chuàng)建了一些屬性,重要的是實(shí)例化了內(nèi)部類(lèi),LazyIterator。最后返回ServiceLoader的實(shí)例。

public final class ServiceLoader<S> implements Iterable<S>
private ServiceLoader(Class<S> svc, ClassLoader cl) {
//要加載的接口
service = Objects.requireNonNull(svc, "Service interface cannot be null");
//類(lèi)加載器
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
//訪問(wèn)控制器
acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
//先清空
providers.clear();
//實(shí)例化內(nèi)部類(lèi)
LazyIterator lookupIterator = new LazyIterator(service, loader);
}
}

查找實(shí)現(xiàn)類(lèi)

查找實(shí)現(xiàn)類(lèi)和創(chuàng)建實(shí)現(xiàn)類(lèi)的過(guò)程,都在LazyIterator完成。當(dāng)我們調(diào)用iterator.hasNext和iterator.next方法的時(shí)候,實(shí)際上調(diào)用的都是LazyIterator的相應(yīng)方法。

public Iterator<S> iterator() {
return new Iterator<S>() {
public boolean hasNext() {
return lookupIterator.hasNext();
}
public S next() {
return lookupIterator.next();
}
.......
};
}

所以,我們重點(diǎn)關(guān)注lookupIterator.hasNext()方法,它最終會(huì)調(diào)用到hasNextService。

private class LazyIterator implements Iterator<S>{
    Class<S> service;
    ClassLoader loader;
    Enumeration<URL> configs = null;
    Iterator<String> pending = null;
    String nextName = null; 
    private boolean hasNextService() {
        //第二次調(diào)用的時(shí)候,已經(jīng)解析完成了,直接返回
        if (nextName != null) {
            return true;
        }
        if (configs == null) {
            //META-INF/services/ 加上接口的全限定類(lèi)名,就是文件服務(wù)類(lèi)的文件
            //META-INF/services/com.viewscenes.netsupervisor.spi.SPIService
            String fullName = PREFIX + service.getName();
            //將文件路徑轉(zhuǎn)成URL對(duì)象
            configs = loader.getResources(fullName);
        }
        while ((pending == null) || !pending.hasNext()) {
            //解析URL文件對(duì)象,讀取內(nèi)容,最后返回
            pending = parse(service, configs.nextElement());
        }
        //拿到第一個(gè)實(shí)現(xiàn)類(lèi)的類(lèi)名
        nextName = pending.next();
        return true;
    }
}

創(chuàng)建實(shí)例

當(dāng)然,調(diào)用next方法的時(shí)候,實(shí)際調(diào)用到的是,lookupIterator.nextService。它通過(guò)反射的方式,創(chuàng)建實(shí)現(xiàn)類(lèi)的實(shí)例并返回。

private class LazyIterator implements Iterator<S>{
private S nextService() {
//全限定類(lèi)名
String cn = nextName;
nextName = null;
//創(chuàng)建類(lèi)的Class對(duì)象
Class<?> c = Class.forName(cn, false, loader);
//通過(guò)newInstance實(shí)例化
S p = service.cast(c.newInstance());
//放入集合,返回實(shí)例
providers.put(cn, p);
return p;
}
}

看到這兒,我想已經(jīng)很清楚了。獲取到類(lèi)的實(shí)例,我們自然就可以對(duì)它為所欲為了!

JDBC中的應(yīng)用

我們開(kāi)頭說(shuō),SPI機(jī)制為很多框架的擴(kuò)展提供了可能,其實(shí)JDBC就應(yīng)用到了這一機(jī)制?;貞浺幌翵DBC獲取數(shù)據(jù)庫(kù)連接的過(guò)程。在早期版本中,需要先設(shè)置數(shù)據(jù)庫(kù)驅(qū)動(dòng)的連接,再通過(guò)DriverManager.getConnection獲取一個(gè)Connection。

String url = "jdbc:mysql:///consult?serverTimezone=UTC";
String user = "root";
String password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);

在較新版本中(具體哪個(gè)版本,筆者沒(méi)有驗(yàn)證),設(shè)置數(shù)據(jù)庫(kù)驅(qū)動(dòng)連接,這一步驟就不再需要,那么它是怎么分辨是哪種數(shù)據(jù)庫(kù)的呢?答案就在SPI。

加載

我們把目光回到DriverManager類(lèi),它在靜態(tài)代碼塊里面做了一件比較重要的事。很明顯,它已經(jīng)通過(guò)SPI機(jī)制, 把數(shù)據(jù)庫(kù)驅(qū)動(dòng)連接初始化了。

public class DriverManager {
  static {
    loadInitialDrivers();
    println("JDBC DriverManager initialized");
  }
}

具體過(guò)程還得看loadInitialDrivers,它在里面查找的是Driver接口的服務(wù)類(lèi),所以它的文件路徑就是:META-INF/services/java.sql.Driver。

public class DriverManager {
    private static void loadInitialDrivers() {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                //很明顯,它要加載Driver接口的服務(wù)類(lèi),Driver接口的包為:java.sql.Driver
                //所以它要找的就是META-INF/services/java.sql.Driver文件
                ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
                Iterator<Driver> driversIterator = loadedDrivers.iterator();
                try{
                    //查到之后創(chuàng)建對(duì)象
                    while(driversIterator.hasNext()) {
                        driversIterator.next();
                    }
                } catch(Throwable t) {
                    // Do nothing
                }
                return null;
            }
        });
    }
}

那么,這個(gè)文件哪里有呢?我們來(lái)看MySQL的jar包,就是這個(gè)文件,文件內(nèi)容為:

com.mysql.cj.jdbc.Driver。

創(chuàng)建實(shí)例

上一步已經(jīng)找到了MySQL中的com.mysql.jdbc.Driver全限定類(lèi)名,當(dāng)調(diào)用next方法時(shí),就會(huì)創(chuàng)建這個(gè)類(lèi)的實(shí)例。它就完成了一件事,向DriverManager注冊(cè)自身的實(shí)例。

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    static {
        try {
            //注冊(cè)
            //調(diào)用DriverManager類(lèi)的注冊(cè)方法
            //往registeredDrivers集合中加入實(shí)例
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }
    public Driver() throws SQLException {
        // Required for Class.forName().newInstance()
    }
}

創(chuàng)建Connection

在DriverManager.getConnection()方法就是創(chuàng)建連接的地方,它通過(guò)循環(huán)已注冊(cè)的數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序,調(diào)用其connect方法,獲取連接并返回。

private static Connection getConnection(
        String url, java.util.Properties info, Class<?> caller) throws SQLException {   
    //registeredDrivers中就包含com.mysql.cj.jdbc.Driver實(shí)例
    for(DriverInfo aDriver : registeredDrivers) {
        if(isDriverAllowed(aDriver.driver, callerCL)) {
            try {
                //調(diào)用connect方法創(chuàng)建連接
                Connection con = aDriver.driver.connect(url, info);
                if (con != null) {
                    return (con);
                }
            }catch (SQLException ex) {
                if (reason == null) {
                    reason = ex;
                }
            }
        } else {
            println("    skipping: " + aDriver.getClass().getName());
        }
    }
}

再擴(kuò)展

既然我們知道JDBC是這樣創(chuàng)建數(shù)據(jù)庫(kù)連接的,我們能不能再擴(kuò)展一下呢?如果我們自己也創(chuàng)建一個(gè)java.sql.Driver文件,自定義實(shí)現(xiàn)類(lèi)MyDriver,那么,在獲取連接的前后就可以動(dòng)態(tài)修改一些信息。

還是先在項(xiàng)目ClassPath下創(chuàng)建文件,文件內(nèi)容為自定義驅(qū)動(dòng)類(lèi)com.viewscenes.netsupervisor.spi.MyDriver我們的MyDriver實(shí)現(xiàn)類(lèi),繼承自MySQL中的NonRegisteringDriver,還要實(shí)現(xiàn)java.sql.Driver接口。這樣,在調(diào)用connect方法的時(shí)候,就會(huì)調(diào)用到此類(lèi),但實(shí)際創(chuàng)建的過(guò)程還靠MySQL完成。

package com.viewscenes.netsupervisor.spi

public class MyDriver extends NonRegisteringDriver implements Driver{
    static {
        try {
            java.sql.DriverManager.registerDriver(new MyDriver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }
    public MyDriver()throws SQLException {}
    
    public Connection connect(String url, Properties info) throws SQLException {
        System.out.println("準(zhǔn)備創(chuàng)建數(shù)據(jù)庫(kù)連接.url:"+url);
        System.out.println("JDBC配置信息:"+info);
        info.setProperty("user", "root");
        Connection connection =  super.connect(url, info);
        System.out.println("數(shù)據(jù)庫(kù)連接創(chuàng)建完成!"+connection.toString());
        return connection;
    }
}
--------------------輸出結(jié)果---------------------
準(zhǔn)備創(chuàng)建數(shù)據(jù)庫(kù)連接.url:jdbc:mysql:///consult?serverTimezone=UTC
JDBC配置信息:{user=root, password=root}
數(shù)據(jù)庫(kù)連接創(chuàng)建完成!com.mysql.cj.jdbc.ConnectionImpl@7cf10a6f

(2)回到SpringFactoriesLoader

借助于Spring框架原有的一個(gè)工具類(lèi):SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自動(dòng)配置功效才得以大功告成!

SpringFactoriesLoader屬于Spring框架私有的一種擴(kuò)展方案,其主要功能就是從指定的配置文件META-INF/spring.factories加載配置,加載工廠類(lèi)。

SpringFactoriesLoader為Spring工廠加載器,該對(duì)象提供了loadFactoryNames方法,入?yún)閒actoryClass和classLoader即需要傳入工廠類(lèi)名稱和對(duì)應(yīng)的類(lèi)加載器,方法會(huì)根據(jù)指定的classLoader,加載該類(lèi)加器搜索路徑下的指定文件,即spring.factories文件。

傳入的工廠類(lèi)為接口,而文件中對(duì)應(yīng)的類(lèi)則是接口的實(shí)現(xiàn)類(lèi),或最終作為實(shí)現(xiàn)類(lèi)。

public abstract class SpringFactoriesLoader {
//...
  public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
    ...
  }
   
   
  public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    ....
  }
}

配合@EnableAutoConfiguration使用的話,它更多是提供一種配置查找的功能支持,即根據(jù)@EnableAutoConfiguration的完整類(lèi)名org.springframework.boot.autoconfigure.EnableAutoConfiguration作為查找的Key,獲取對(duì)應(yīng)的一組@Configuration類(lèi)

上圖就是從SpringBoot的autoconfigure依賴包中的META-INF/spring.factories配置文件中摘錄的一段內(nèi)容,可以很好地說(shuō)明問(wèn)題。

(重點(diǎn))所以,@EnableAutoConfiguration自動(dòng)配置的魔法其實(shí)就變成了:

從classpath中搜尋所有的META-INF/spring.factories配置文件,并將其中
org.springframework.boot.autoconfigure.EnableAutoConfiguration對(duì)應(yīng)的
配置項(xiàng)通過(guò)反射(Java Refletion)實(shí)例化為對(duì)應(yīng)的標(biāo)注了@Configuration的JavaConfig形式的IoC容器配置類(lèi),然后匯總為一個(gè)并加載到IoC容器。

第3章 補(bǔ)充內(nèi)容

  • @Target 注解可以用在哪。TYPE表示類(lèi)型,如類(lèi)、接口、枚舉@Target(ElementType.TYPE) //接口、類(lèi)、枚舉@Target(ElementType.FIELD) //字段、枚舉的常量@Target(ElementType.METHOD) //方法@Target(ElementType.PARAMETER) //方法參數(shù)@Target(ElementType.CONSTRUCTOR) //構(gòu)造函數(shù)@Target(ElementType.LOCAL_VARIABLE)//局部變量@Target(ElementType.ANNOTATION_TYPE)//注解@Target(ElementType.PACKAGE) ///包
  • @Retention 注解的保留位置。只有RUNTIME類(lèi)型可以在運(yùn)行時(shí)通過(guò)反射獲取其值@Retention(RetentionPolicy.SOURCE) //注解僅存在于源碼中,在class字節(jié)碼文件中不包含@Retention(RetentionPolicy.CLASS) // 默認(rèn)的保留策略,注解會(huì)在class字節(jié)碼文件中存在,但運(yùn)行時(shí)無(wú)法獲得,@Retention(RetentionPolicy.RUNTIME) // 注解會(huì)在class字節(jié)碼文件中存在,在運(yùn)行時(shí)可以通過(guò)反射獲取到
  • @Documented 該注解在生成javadoc文檔時(shí)是否保留
  • @Inherited 被注解的元素,是否具有繼承性,如子類(lèi)可以繼承父類(lèi)的注解而不必顯式的寫(xiě)下來(lái)。
責(zé)任編輯:姜華 來(lái)源: 今日頭條
相關(guān)推薦

2022-08-08 07:33:11

自動(dòng)裝配Java容器

2009-06-18 11:15:53

裝配beanxml配置Spring

2024-05-29 07:47:30

SpringJava@Resource

2023-11-01 09:07:01

Spring裝配源碼

2023-10-07 09:16:55

SpringBoot啟動(dòng)流程

2025-01-02 15:08:36

SpringBoot自動(dòng)配置Java

2023-10-10 09:07:23

2021-06-17 08:05:59

SpringBoot條件裝配

2024-04-26 08:46:42

Spring自動(dòng)裝配核心內(nèi)容

2023-09-08 09:10:33

SpringBoot微服務(wù)架構(gòu)

2011-03-30 15:05:40

MRTG安裝

2011-04-02 15:26:51

Cacti安裝

2011-11-08 21:55:58

MRTG 配置

2011-03-25 13:40:28

Cacti安裝配置

2011-04-02 15:26:58

Cacti安裝

2011-04-02 15:17:59

2023-03-23 08:11:59

2010-09-06 14:32:55

CISCO PPP配置

2011-03-24 13:00:30

2022-09-27 07:31:57

Property模式數(shù)據(jù)
點(diǎn)贊
收藏

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