• 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. 基于 react 的Java web 应用—— 组件复用(后续需更新)

    前言 实习第二周,被告知要用React与导师进行基于React的Javaweb 的开发,jinzhangaaaaa~由于React 这款框架没学过,看了一峰老师的基础入门教程,硬着头皮开始上了... ...

  2. libevent(六)http server

    客户端: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signa ...

  3. shell字符串索引

    shell中的字符串索引一会从0开始,一会从1开始,见例子: #!/bin/bash string="hello world" length=${#string} echo &qu ...

  4. 搜索+简单dp

    前言:即使是简单的递归,在复杂度过高时也可以使用简单的dp. 一般有两种情况,一是利用dp思想求最优子结构进行搜索剪枝,二是利用搜索进行dp数组的填充. 例题一.hdu1978 题目大意:这是一个简单 ...

  5. C - A Plug for UNIX POJ - 1087 网络流

    You are in charge of setting up the press room for the inaugural meeting of the United Nations Inter ...

  6. Spring官网阅读(十七)Spring中的数据校验

    文章目录 Java中的数据校验 Bean Validation(JSR 380) 使用示例 Spring对Bean Validation的支持 Spring中的Validator 接口定义 UML类图 ...

  7. 视频文件自动转rtsp流

    最近碰到一个项目需要用到 rtsp 视频流做测试, 由于真实环境的 摄像头 并不能满足需求,故尝试了一下用本地视频文件转换成rtsp视频流做测试,记录一下~ 采用方案: Docker + EasyDa ...

  8. 201771030117-祁甜 实验一 软件工程准备—<阅读《现代软件工程——构建之法》提出的三个问题>

    项目 内容 课程班级博客链接 https://edu.cnblogs.com/campus/xbsf/nwnu2020SE 这个作业要求链接 https://www.cnblogs.com/nwnu- ...

  9. C++11之STL多线程

    STL库跨平台: VS2010不支持std::thread库,至少VS2012/2013及其以上可以: 一.库概要 (1)std::thread成员函数 thread(fun, args...); / ...

  10. 绝对一个月精通vue

    马上从vue-cli4练手,要不然,学几年,你也不懂组件式开发,不懂VUEX,不懂路由, 也许你会说你懂, 麻烦你花一个月学vue-cli4以一个完整购物商城来练手,   一个月后,如果还觉得我错,我 ...