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();
}
}
SpringBoot自定义装配的多种实现方法的更多相关文章
- SpringBoot自动装配-自定义Start
SpringBoot自动装配 在没有使用SpringBoot之前,使用ssm时配置redis需要在XML中配置端口号,地址,账号密码,连接池等等,而使用了SpringBoot后只需要在applicat ...
- springboot自动装配
Spring Boot自动配置原理 springboot自动装配 springboot配置文件 Spring Boot的出现,得益于“习惯优于配置”的理念,没有繁琐的配置.难以集成的内容(大多数流行第 ...
- 一步步从Spring Framework装配掌握SpringBoot自动装配
目录 Spring Framework模式注解 Spring Framework@Enable模块装配 Spring Framework条件装配 SpringBoot 自动装配 本章总结 Spring ...
- SpringBoot启动流程分析(五):SpringBoot自动装配原理实现
SpringBoot系列文章简介 SpringBoot源码阅读辅助篇: Spring IoC容器与应用上下文的设计与实现 SpringBoot启动流程源码分析: SpringBoot启动流程分析(一) ...
- SpringBoot自动装配原理解析
本文包含:SpringBoot的自动配置原理及如何自定义SpringBootStar等 我们知道,在使用SpringBoot的时候,我们只需要如下方式即可直接启动一个Web程序: @SpringBoo ...
- Spring Boot之从Spring Framework装配掌握SpringBoot自动装配
Spring Framework模式注解 模式注解是一种用于声明在应用中扮演“组件”角色的注解.如 Spring Framework 中的 @Repository 标注在任何类上 ,用于扮演仓储角色的 ...
- springboot自动装配原理
最近开始学习spring源码,看各种文章的时候看到了springboot自动装配实现原理.用自己的话简单概括下. 首先打开一个基本的springboot项目,点进去@SpringBootApplica ...
- SpringBoot | 2.1 SpringBoot自动装配原理
@ 目录 前言 1. 引入配置文件与配置绑定 @ImportResource @ConfigurationProperties 1.1 @ConfigurationProperties + @Enab ...
- Java之SpringBoot自定义配置与整合Druid
Java之SpringBoot自定义配置与整合Druid SpringBoot配置文件 优先级 前面SpringBoot基础有提到,关于SpringBoot配置文件可以是properties或者是ya ...
随机推荐
- 【阅读笔记】Ranking Relevance in Yahoo Search (四 / 完结篇)—— recency-sensitive ranking
7. RECENCY-SENSITIVE RANKING 作用: 为recency-sensitive的query提高排序质量: 对于这类query,用户不仅要相关的还需要最新的信息: 方法:rece ...
- C++ FAQ
空类 class A { }; // sizeof(A) = 1 空类的大小之所以为1,因为标准规定完整对象的大小>0,否则两个不同对象可能拥有相同的地址,故编译器会生成1B占位符. 那么两个对 ...
- python(格式化输出)
一.%格式化输出 1.整数的输出(参照ASCII) %o —— oct 八进制 %d —— dec 十进制(digit ) %x —— hex 十六进制 >>> print('%o' ...
- 题解 CF588A 【Duff and Meat】
题意 有一个人,想吃 $n$ 天肉,第 $i$ 天需要吃 $a[i]$ 块肉,第 $i$ 天超市肉价为每块 $b[i]$ 元,买来的肉可以留到后面吃,求这个人在每天都吃到肉的情况下花费的最小值. 题目 ...
- redis系列之2----详细讲解redis数据结构(内存模型)以及常用命令
Redis数据类型 与Memcached仅支持简单的key-value结构的数据记录不同,Redis支持的数据类型要丰富得多,常用的数据类型主要有五种:String.List.Hash.Set和Sor ...
- Oracle条件判断
一. if/else 语法:if 条件表达式 then语句块:if 条件表达式 then 语句块end if;elsif 条件表达式 then语句块:...else语句块:end if;举例:输入一个 ...
- GitHub上Asp.Net Core的源代码
记录,备查. https://github.com/aspnet/AspNetCore/tree/master/src
- apply call bind的用法与实现
概念 apply call 和bind 允许为不同的对象分配和调用属于一个对象的函数/方法.同时它们可以改变函数内 this 的指向. 区别 apply 和 call 接收的参数形式不同 apply ...
- Mysql常用sql语句(13)- having 过滤分组结果集
测试必备的Mysql常用sql语句,每天敲一篇,每次敲三遍,每月一循环,全都可记住!! https://www.cnblogs.com/poloyy/category/1683347.html 前言 ...
- 房价预测Task1
pandas:简单的房价预测实例 我们使用pandas等工具,对于给出的.csv文件进行处理,完成要求的几个Task. 利用sklearn的线性回归,对于房价进行简单的预测. 所有的要求,数据集等文件 ...