• 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(); }
}
 

SpringBoot自定义装配的多种实现方法的更多相关文章

  1. SpringBoot自动装配-自定义Start

    SpringBoot自动装配 在没有使用SpringBoot之前,使用ssm时配置redis需要在XML中配置端口号,地址,账号密码,连接池等等,而使用了SpringBoot后只需要在applicat ...

  2. springboot自动装配

    Spring Boot自动配置原理 springboot自动装配 springboot配置文件 Spring Boot的出现,得益于“习惯优于配置”的理念,没有繁琐的配置.难以集成的内容(大多数流行第 ...

  3. 一步步从Spring Framework装配掌握SpringBoot自动装配

    目录 Spring Framework模式注解 Spring Framework@Enable模块装配 Spring Framework条件装配 SpringBoot 自动装配 本章总结 Spring ...

  4. SpringBoot启动流程分析(五):SpringBoot自动装配原理实现

    SpringBoot系列文章简介 SpringBoot源码阅读辅助篇: Spring IoC容器与应用上下文的设计与实现 SpringBoot启动流程源码分析: SpringBoot启动流程分析(一) ...

  5. SpringBoot自动装配原理解析

    本文包含:SpringBoot的自动配置原理及如何自定义SpringBootStar等 我们知道,在使用SpringBoot的时候,我们只需要如下方式即可直接启动一个Web程序: @SpringBoo ...

  6. Spring Boot之从Spring Framework装配掌握SpringBoot自动装配

    Spring Framework模式注解 模式注解是一种用于声明在应用中扮演“组件”角色的注解.如 Spring Framework 中的 @Repository 标注在任何类上 ,用于扮演仓储角色的 ...

  7. springboot自动装配原理

    最近开始学习spring源码,看各种文章的时候看到了springboot自动装配实现原理.用自己的话简单概括下. 首先打开一个基本的springboot项目,点进去@SpringBootApplica ...

  8. SpringBoot | 2.1 SpringBoot自动装配原理

    @ 目录 前言 1. 引入配置文件与配置绑定 @ImportResource @ConfigurationProperties 1.1 @ConfigurationProperties + @Enab ...

  9. Java之SpringBoot自定义配置与整合Druid

    Java之SpringBoot自定义配置与整合Druid SpringBoot配置文件 优先级 前面SpringBoot基础有提到,关于SpringBoot配置文件可以是properties或者是ya ...

随机推荐

  1. 以内存级速度实现存储?XPoint正是我们的计划

    随着计算能力虚拟化技术的普及,存储机制在速度上远逊于内存这一劣势开始变得愈发凸显. 这一巨大的访问速度鸿沟一直是各项存储技术想要解决的核心难题:纸带.磁带.磁盘驱动器乃至闪存记忆体等等,而如今最新一代 ...

  2. JS基础入门篇(十)— 数组方法

    1.join 作用: 将数组通过指定字符拼接成字符串.语法: string arr.join([separator = ',']);参数: separator可选,如果省略的话,默认为一个逗号.如果 ...

  3. C# 基础知识系列- 15 异常处理篇

    0. 前言 为什么我们需要异常处理?什么是异常? 在汉语中,异常指非正常的:不同于平常的.翻译到程序中,就是指会导致程序无法按照既定逻辑运行的意外,或者说是错误.可能会有小伙伴好奇了,我们的程序不是正 ...

  4. file download hash mismatch

    在linux中使用cmake时,遇到了"file download hash mismatch",同时status显示"unsupported protocol" ...

  5. spring学习笔记(五)自定义spring-boot-starter(1)

    在我们开始定义之前我们应该知道springBoot的大致运行原理,我们从springBoot启动类开始.首先我们看下这个注解,@SpringBootApplication,跟进去可以看到如下代码: @ ...

  6. vue-双向响应数据底层原理分析

    总所周知,vue的一个大特色就是实现了双向数据响应,数据改变,视图中引用该数据的部分也会自动更新 一.双向数据绑定基本思路 “数据改变,视图中引用该数据的部分也会自动更新“,从这句话,我们可以分析出以 ...

  7. js基石之---es7的decorator修饰器

    es7的decorator修饰器 装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法. decorator就是给类添加或修改类的变量与方法的. 装饰器是一种函数, ...

  8. pyhanlp安装教程

    1.hanlp简介 HanLP是由一系列模型与算法组成的Java工具包,目标是普及自然语言处理在生产环境中的应用.HanLP具备功能完善.性能高效.架构清晰.语料时新.可自定义的特点. Hanlp具有 ...

  9. Spring JDBC 框架使用JdbcTemplate 类的一个实例

    JDBC 框架概述 在使用普通的 JDBC 数据库时,就会很麻烦的写不必要的代码来处理异常,打开和关闭数据库连接等.但 Spring JDBC 框架负责所有的低层细节,从开始打开连接,准备和执行 SQ ...

  10. FPGA六位共阳极数码管动态显示

    `timescale 1ns/1ps module adc_dis( clk , rst_n , sm_seg , sm_bit ); input clk;//50HZ input rst_n; :] ...