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 ...
随机推荐
- 流畅的python读书笔记-第十章-继承优缺点
继承的优缺点 推出继承的初衷是让新手顺利使用只有专家才能设计出来的框架.--Alan Kay 子类化内置类型很麻烦 (如 list 或 dict)) ,别搞这种 直接子类化内置类型(如 dict.li ...
- celery的定时任务
定时任务 Celery 中启动定时任务有两种方式,(1)在配置文件中指定:(2)在程序中指定. # cele.py import celery app = celery.Celery('cele', ...
- 《Docker从入门到跑路》之Dockerfile基本操作
一.简介 Dockerfile是一个文本文件,里面包含一条条指令,每一条指令就是一层镜像.一般情况下,Dockerfile分为4个部分: 基础镜像 维护者信息 镜像操作指令 容器启动时执行命令 例如: ...
- OSG程序设计之Hello World 2.0
现在为Hello World添加一些键盘响应事件. //需要多添加两个库:osgGAd.lib.osgd.lib 代码如下: #include <osgDB/ReadFile> #incl ...
- 复数(complex)
表示复数信息 a = 12.3+4j print('a的类型为:', type(a)) # 运行结果:a的类型为: <class 'complex'> print(a.real) # 实部 ...
- 从excel表格加载数据返回DataSet
添加命名空间:using System.Data.OleDb; /// <summary> /// 从excel表格加载数据返回DataSet /// </summary> / ...
- HTTP头部信息和错误代码详解-《HTTP权威指南》
最近在调试 前后端分离的请求测试,遇到了一个405错误, 无法接受,于是开始了人肉搜索405. 最后 还是HTTP头部信息里的Accept:application/json 这个Accept 导致的, ...
- java制作甘特图
今日来做一下甘特图.网上搜到了这个源码,但是导的jar包,并没有给我.swiftganttdemo但是名为swiftgantt制作:所以灵机一动在网上搜到了swiftangantt组件:在组件中找到了 ...
- React Native超简单完整示例-tabs、页面导航、热更新、用户行为分析
初学React Native,如果没有人指引,会发现好多东西无从下手,但当有人指引后,会发现其实很简单.这也是本人写这篇博客的主要原因,希望能帮到初学者. 本文不会介绍如何搭建开发环境,如果你还没有搭 ...
- 06_CSS入门和高级技巧(4)
复习 CSS : 负责样式层,层叠式样式表cascading style sheet.CSS2.1,最新版本CSS3. CSS选择器: 选择哪些元素加样式.基本选择3种:标签p.id选择器#id.cl ...