SpringBoot自定义装配的多种实现方法

  • Spring手动装配实现
    • 对于需要加载的类文件,使用@Configuration/@Component/@Service/@Repository修饰
@Configuration
public class RedisConfig {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, User2> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, User2> template = new RedisTemplate<String, User2>();
//        template.setConnectionFactory(jedisConnectionFactory());
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
}
    •  扫描需要加载的Bean的包路径
    • XML实现
<context:component-scan base-package="your.pkg"/>
    • Annotations实现
@ComponentScan(basePackages = "com.gara.sb.service")
  • @Profile实现
    • Profile指的是当一个或多个指定的Profile被激活时,加载对应修饰的Bean,代码如下
@Profile("Java8")
@Service
@Slf4j
public class Java8CalculateService implements CalculateService {
    @Override
    public Integer sum(Integer... values) {
        log.info("Java8 Lambda实现");
        Integer sum = Stream.of(values).reduce(0, Integer::sum);
        return sum;
    }
}

  

    • 引导类测试:当我们在启动时,指定Profile,会自动装载 Java8CalculateService 
// 这里要Bean对应的包路径扫描
@ComponentScan(basePackages = "com.gara.sb.service") public class ProfileBootStrap { public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(ProfileBootStrap.class) .web(WebApplicationType.NONE) .profiles("Java8") .run(args); CalculateService calculateService = context.getBean(CalculateService.class); System.out.println("CalculateService with Profile Java8: " + calculateService.sum(0, 1, 2, 3, 4, 5)); context.close(); } }
  • @EnableXxx实现:自定义EnableHelloWorld实现Bean自动装配
    • 首先自定义注解,导入核心配置类
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(CoreConfig.class)
//@Import(HelloWorldImportSelector.class)
public @interface EnableHelloWorld {
}
@Configuration
//@Import(value = CommonConfig.class)
public class CoreConfig {

    @Bean
    public String helloWorld(){ // 方法名即Bean名
        return "Hello World 2020";
    }
}

这种方式直接,但是不够灵活,推荐第二种方式:@interface + ImportSelector实现

    • 自定义HelloWorldImportSelector 需要实现ImportSelector接口
public class HelloWorldImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // 这里可以加上分支判断和其他逻辑处理
        return new String[]{CoreConfig.class.getName()};
    }
}
    • 引导类测试
@EnableHelloWorld
public class EnableHelloWorldBootStrap {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootStrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
        String helloWorld = context.getBean("helloWorld", String.class);
        System.out.println(helloWorld);
        context.close();
    }
}
  • ConditionalOnXxx实现
    • 自定义Conditional注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {

    String name();

    String value();
}
    • 自定义Condition
public class OnSystemPropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
        List<Object> nameProperty = attributes.get("name");
        List<Object> valueProperty = attributes.get("value");

        Object property = System.getProperty(String.valueOf(nameProperty.get(0)));

        return property.equals(valueProperty.get(0));
    }
}
    • 引导类测试
public class ConditionalBootStrap {


    @ConditionalOnSystemProperty(name = "user.name", value = "yingz")
    @Bean
    public String syaHi(){
        return "Hello from sayHi()";
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalBootStrap.class)
                .web(WebApplicationType.NONE)
//                .profiles("Java8")
                .run(args);

        String syaHi = context.getBean("syaHi", String.class);

        System.out.println(syaHi);

        context.close();

    }
}
 

猜你喜欢

转载自www.cnblogs.com/gara/p/12964159.html
今日推荐