Spring 注解驱动(一)基本使用规则
Spring 注解驱动(一)基本使用规则
Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html)
一、基本使用
@Configuration
@ComponentScan(basePackages = "com.github.binarylei",
excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = {Controller.class})}
)
@Lazy(false)
public class AnnnotationConfig {
// Scope 可取四个值:SCOPE_SINGLETON、SCOPE_PROTOTYPE、SCOPE_SESSION、SCOPE_REQUEST
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public User user() {
return new User();
}
}
启动测试:
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnnotationConfig.class);
// AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// context.register(AnnnotationConfig.class);
// context.refresh();
User user = context.getBean(User.class);
}
二、@ComponentScan
@Configuration
@ComponentScan(basePackages = "com.github.binarylei",
excludeFilters = {
@Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {User.class}),
@Filter(type = FilterType.CUSTOM,classes = MyFilter.class)
}, useDefaultFilters = false
)
public class AnnnotationConfig {
}
自定义的包扫描如下:
public class MyFilter implements TypeFilter {
/**
* @param metadataReader 当前类的信息
* @param metadataReaderFactory 获取其他类的信息
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
// 1. 当前类的注解信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
// 2. 当前类的信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
// 3. 当前类的资源信息(类路径)
Resource resource = metadataReader.getResource();
return true;
}
}
三、@Conditional
@Bean
@Conditional(MyCondition.class)
public User user() {
return new User();
}
// 条件装配
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 1. IOC 容器
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 2. 类加载器
ClassLoader classLoader = context.getClassLoader();
// 3. 环境变量
Environment environment = context.getEnvironment();
// 4. 可以向容器中注册 BeanDefinition
BeanDefinitionRegistry registry = context.getRegistry();
return environment.getProperty("os.name").contains("Windows");
}
}
四、@Import
给容器中注册组件有以下方式:
- @Bean
- 包扫描(@ComponentScan) + 注解(@Componet/@Repository/@Service/@Controller)
- @Import
- @Import({User.class}) 导入单个组件
- @Import({User.class, MyImportSelector.class}) MyImportSelector 批量导入组件
- @Import({User.class, MyImportBeanDefinitionRegistrar.class}) MyImportBeanDefinitionRegistrar 批量导入组件
- FactoryBean
@Import({User.class, MyImportSelector.class})
@Import({User.class, MyImportBeanDefinitionRegistrar.class})
public class AnnnotationConfig {
}
// 返回类名的全定限名称
public class MyImportSelector implements ImportSelector {
/**
* @param importingClassMetadata 获取标注 @Import 注解的类所有注解信息(不仅仅是 @Import)
*/
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// 不要返回 null,否则会报空指针异常
return new String[]{User.class.getName()};
}
}
// 使用 BeanDefinitionRegistry 注册
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
/**
* @param importingClassMetadata 获取标注 @Import 注解的类所有注解信息(不仅仅是 @Import)
* @param registry 向容器中注册 BeanDefinition
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
boolean definition1 = registry.containsBeanDefinition("red");
boolean definition2 = registry.containsBeanDefinition("blue");
if (definition1 && definition2) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(User.class);
registry.registerBeanDefinition("user", beanDefinition);
}
}
}
五、Bean 的生命周期
- @Bean(initMethod = "init", destroyMethod = "destroy")
- 实现 InitializingBean, DisposableBean 接口
每天用心记录一点点。内容也许不重要,但习惯很重要!
Spring 注解驱动(一)基本使用规则的更多相关文章
- 【Spring注解驱动开发】组件注册-@ComponentScan-自动扫描组件&指定扫描规则
写在前面 在实际项目中,我们更多的是使用Spring的包扫描功能对项目中的包进行扫描,凡是在指定的包或子包中的类上标注了@Repository.@Service.@Controller.@Compon ...
- 【Spring注解驱动开发】自定义TypeFilter指定@ComponentScan注解的过滤规则
写在前面 Spring的强大之处不仅仅是提供了IOC容器,能够通过过滤规则指定排除和只包含哪些组件,它还能够通过自定义TypeFilter来指定过滤规则.如果Spring内置的过滤规则不能够满足我们的 ...
- 0、Spring 注解驱动开发
0.Spring注解驱动开发 0.1 简介 <Spring注解驱动开发>是一套帮助我们深入了解Spring原理机制的教程: 现今SpringBoot.SpringCloud技术非常火热,作 ...
- 【spring 注解驱动开发】spring组件注册
尚学堂spring 注解驱动开发学习笔记之 - 组件注册 组件注册 1.@Configuration&@Bean给容器中注册组件 2.@ComponentScan-自动扫描组件&指定扫 ...
- 你真的知道Spring注解驱动的前世今生吗?这篇文章让你豁然开朗!
本篇文章,从Spring1.x到Spring 5.x的迭代中,站在现在的角度去思考Spring注解驱动的发展过程,这将有助于我们更好的理解Spring中的注解设计. Spring Framework ...
- Spring 注解驱动(二)Servlet 3.0 注解驱动在 Spring MVC 中的应用
Spring 注解驱动(二)Servlet 3.0 注解驱动在 Spring MVC 中的应用 Spring 系列目录(https://www.cnblogs.com/binarylei/p/1019 ...
- 1、课程简介-Spring 注解驱动开发
1.课程简介-Spring 注解驱动开发
- 【Spring注解驱动开发】聊聊Spring注解驱动开发那些事儿!
写在前面 今天,面了一个工作5年的小伙伴,面试结果不理想啊!也不是我说,工作5年了,问多线程的知识:就只知道继承Thread类和实现Runnable接口!问Java集合,竟然说HashMap是线程安全 ...
- 【Spring注解驱动开发】使用@Scope注解设置组件的作用域
写在前面 Spring容器中的组件默认是单例的,在Spring启动时就会实例化并初始化这些对象,将其放到Spring容器中,之后,每次获取对象时,直接从Spring容器中获取,而不再创建对象.如果每次 ...
随机推荐
- python文件操作之二进制
列表项 三元运算符号: a=3 b=7 val=a if a>b else val=b print(val) 文件处理 首先给你一个文件,或者自己建立一个文件,那如何查看文件的内容呢? 1.安装 ...
- NBU 还原LINUX ORACLE 数据库(EHR)
一.E-HR数据库(全备)恢复 目录 一.E-HR数据库(全备)恢复... 1 1. 使用bplist 命令读取备份文件... 1 2. 启动到nomount状态... 2 3. 利用rman还原控制 ...
- tomcat 启动报错org.hibernate.cfg.annotations.SimpleValueBinder.setType
url: https://blog.csdn.net/zhx_0323/article/details/78844323 # A fatal error has been detected by th ...
- JMeter学习(九)FTP测试计划(转载)
转载自 http://www.cnblogs.com/yangxia-test FTP服务主要提供上传和下载功能.有时间需要我们测试服务器上传和下载的性能.在这里我通过JMeter做一个FTP测试计划 ...
- 【scrapy】爬虫的时候总在提示 KeyError: 'novelLabel'
调试的时候总是提示 KeyError: 'novelLabel'然后决定断点调试一下, 在def parse_book_list(self, response):方法下,添加print(respons ...
- STL::map/multimap
map: 默认根据 key 排序(从小到大),能够通过 backet operator(operator [ ]) 来获取元素,内部由二叉搜索树来实现(binary search trees). mu ...
- HDU-1087.SuperJUmpingJUmpingJumping.(DP and LISPP)
本题大意:给定一个长度为n的序列a,让你输出这个序列子序列中元素和最大的最大上升子序列. 本题思路:一开始肯定可以想到用LIS实现,我们用LIS实现的时候可以发现这个问题并不满足LIS问题的最优子结构 ...
- Codeforces Beta Round #52 (Div. 2)
Codeforces Beta Round #52 (Div. 2) http://codeforces.com/contest/56 A #include<bits/stdc++.h> ...
- Ionic3错误: StaticInjectorError[HttpModule]: NullInjectorError: No provider for HttpModule!
先在app.module.ts中导入HttpModule,才能在构造函数中注入Http. Ionic自动构建项目时,并没有导入HttpModule. 解决方案:打开app.module.ts,加入导入 ...
- TZOJ 4912 炮兵阵地(状压dp)
描述 司令部的将军们打算在N*M的网格地图上部署他们的炮兵部队.一个N*M的地图由N行M列组成,地图的每一格可能是山地(用"H" 表示),也可能是平原(用"P" ...