springboot实现自定义自动装配

实现方法

  1. 激活自动装配 - @EnableAutoConfiguration
  2. 实现自动装配 - XXXAutoConfiguration
  3. 配置自动装配实现 - META-INF/spring.factories

1、Springboot服务引导类

@EnableAutoConfiguration
public class MyAutoConfigruationBootStrap {
          
   

    public static void main(String[] args) {
          
   
        ConfigurableApplicationContext context = new SpringApplicationBuilder(MyAutoConfigruationBootStrap.class)
                .web(WebApplicationType.NONE)   //不开启web模式
                .run(args);

        String helloWorld = context.getBean("HelloWorld", String.class);
        System.err.println("获取到了bean对象====="+helloWorld);

        //关闭容器
        context.close();
    }
}

2、HelloWorldAutoConfiguration 自动装配类

@Configuration //模式注解表示配置类
@EnableHelloWord //激活helloworld装配
@MyCondition(name = "userName",value = "xiao") //条件装配,满足条件才会激活HelloWord模块
public class HelloWorldAutoConfiguration {
          
   


}

3、 META-INF/spring.factories

# 实现自动装配
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.zixue.springboottest.configration.HelloWorldAutoConfiguration

4、定义条件装配,及具体规则

@Target({
          
    ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(MyPropertiesCondition.class)
public @interface MyCondition {
          
   

    /** 属性名称*/
    String name();

    /** 属性名称*/
    String value();

}
public class MyPropertiesCondition implements Condition {
          
   

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
          
   
        // annotatedTypeMetadata 源信息可以获取 MyCondition注解的属性数据
        Map<String, Object> attributes = annotatedTypeMetadata.getAnnotationAttributes(MyCondition.class.getName());
        if ("userName".equals(attributes.get("name")) && "xiao".equals(attributes.get("value"))){
          
   
            return true;
        }
        return false;
    }
}

5、激活helloworld模块装配,通过ImportSelector 注入bean

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(MyImportSelector.class)
public @interface EnableHelloWord {
          
   
}
public class MyImportSelector implements ImportSelector {
          
   


    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
          
   
        System.err.println("--------运行了自定义的MyImportSelector -----------");
        return new String[]{
          
   HelloWordConfiguration.class.getName()};
    }
}
@Configuration
public class HelloWordConfiguration {
          
   

    @Bean
    public String HelloWorld(){
          
   
        return "Hello world 2020.............";
    }
}

6、运行结果

.   ____          _            __ _ _
 /\ / ____ __ _ _(_)_ __  __ _    
( ( )\___ | _ | _| | _ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
    |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.0)

2020-11-26 15:22:12.446  INFO 10600 --- [           main] c.z.s.b.MyAutoConfigruationBootStrap     : Starting MyAutoConfigruationBootStrap using Java 1.8.0_144 on DESKTOP-JS1AHB8 with PID 10600 (D:springBootProjectspringbootTest	argetclasses started by xiao in D:springBootProjectspringbootTest)
2020-11-26 15:22:12.452  INFO 10600 --- [           main] c.z.s.b.MyAutoConfigruationBootStrap     : No active profile set, falling back to default profiles: default
--------运行了自定义的MyImportSelector -----------
2020-11-26 15:22:13.984  INFO 10600 --- [           main] c.z.s.b.MyAutoConfigruationBootStrap     : Started MyAutoConfigruationBootStrap in 2.404 seconds (JVM running for 4.762)
获取到了bean对象=====Hello world 2020.............
经验分享 程序员 微信小程序 职场和发展