springboot实现自动装配

首先创建一个maven工程并依赖spring-context

pom.xml




  4.0.0

  com.david.my
  mycode
  1.0-SNAPSHOT

  mycode
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
  

  
    
      junit
      junit
      4.11
      test
    
    
      org.springframework
      spring-context
      4.3.16.RELEASE
    
  


 创建一个java类,并实现简单功能

public class MyCode {

    public String doCode(){

        return "this is my code";
    }
}

 创建一个spring配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {

    @Bean
    public MyCode myCode(){
        return new MyCode();
    }
}

springboot预留了扩展点(SPI),通过在资源路径下创建META-INF文件夹,在META-INF下创建spring.factories文件,spring启动时会扫描所有资源文件下的这个文件,并根据文件配置内容加载对应bean的信息交由spring管理,这样我们就能使用autowired的注解实现快速注入使用。starter就是根据这个原理实现的

spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.david.my.MyConfig

整体项目结构如下图

springboot实现自动装配_第1张图片

然后把项目install成jar

重新创建一个springboot项目并依赖打包的jar

新项目pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.4.RELEASE
         
    
    com.david
    my-web
    0.0.1-SNAPSHOT
    my-web
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.david.my
            mycode
            1.0-SNAPSHOT
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


创建一个controller并使用@Autowired注解注入MyCode


@RestController
public class MyController {

    @Autowired
    MyCode myCode;

    @RequestMapping("/mycode")
    public String mycode(){
        return myCode.doCode();
    }
}

启动后访问

springboot实现自动装配_第2张图片

源码跟踪:

进入SpringBootApplication.class

springboot实现自动装配_第3张图片

进入EnableAutoConfiguration.class

springboot实现自动装配_第4张图片

进入AutoConfigurationImportSelector.class

springboot实现自动装配_第5张图片

在下面这个方法中会加载所有spring.factories文件内容

 protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List 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;
    }

 

你可能感兴趣的:(springboot)