• 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. AngularJS学习1-基础知识

    Angular并不是适合任何应用的开发,Angular考虑的是构建CRUD应用 但是目前好像也只是用到了angular的一些指令,数据绑定,mvc,http服务而已..... 以前传统的做法就是,通过 ...

  2. 数学--数论--HDU - 6124 Euler theorem (打表找规律)

    HazelFan is given two positive integers a,b, and he wants to calculate amodb. But now he forgets the ...

  3. CodeForces - 1047CEnlarge GCD(这题很难,快来看题解,超级详细,骗浏览量)

    C. Enlarge GCD time limit per test1 second memory limit per test256 megabytes inputstandard input ou ...

  4. webpack----js的静态模块打包器

    webpack----js的静态模块打包器 博客说明 文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢! 简介 webpack 是一个现代 J ...

  5. Pycharm修改HTML模板

  6. Spring源码阅读 之 搭建源码阅读环境(IDEA)

    检出源码: GitHub:https://github.com/spring-projects/spring-framework.git 可以按如下步骤:(须确保Git已正确安装) Git正确安装后, ...

  7. Django 设置admin后台表和App(应用)为中文名

    设置表名为中文 1.设置Models.py文件 class Post(models.Model): name = models.CharField() --省略其他字段信息 class Meta: v ...

  8. 【Scala】什么是隐式转换?它又能用来干嘛?该怎么用

    文章目录 定义 隐式参数 隐式转换 隐式值:给方法提供参数 隐式视图 将Int和Double类型转换为String 狗狗学技能(使用别的类中的方法) 使用规则 定义 隐式参数 隐式参数指在函数或者方法 ...

  9. Mysql常用sql语句(九)- like 模糊查询

    测试必备的Mysql常用sql语句,每天敲一篇,每次敲三遍,每月一循环,全都可记住!! https://www.cnblogs.com/poloyy/category/1683347.html 前言 ...

  10. Ubuntu 1804 安装xmind8详细过程

    安装比较简单, 折腾了很久,一启动就报错,切换了JDK版本就能用了: 安装 登陆官网,下载xmind8: 下载得到文件xmind-8-update9-linux.zip: 将文件解压至路径xmind下 ...