基于注解和类的组件注册

@Conditional

作用:按照一定的条件进行判断,如果满足条件的话就给spring容器中注册bean

​ 该注解既可以标注到方法上面,也可以标注到类上面(只有满足条件时,当前类中配置的bean才能注册)

属性:Class<? extends Condition>[] value()

​ value属性需要创建一个实现Condition接口的类并且重写其中的matches方法

public class testCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return false;
    }
}

示例:想要实现如果当前是在windows系统下就注册bill如果是在linux下就注册linus

MyConfig配置类

@Configuration
@ComponentScan("com.zl")
public class MainConfig {

    @Bean("bill")
    @Conditional(WindowsCondition.class)
    public Person person01(){
        return new Person("bill",50);
    }
    @Bean("linus")
    @Conditional(LinuxCondition.class)
    public Person person02(){
        return new Person("linus",49);
    }
}

WindowsCondition

public class WindowsCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");
        if (property.contains("Windows")){
            return true;
        }
        return false;
    }
}

LinuxCondition

public class LinuxCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");
        if (property.contains("Linux")){
            return true;
        }
        return false;
    }
}

测试类

public class IocTest {
    private ApplicationContext applicationContext;

    @Before
    public void init(){
        applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
    }
    @Test
    public void testConditional(){
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }
}
//因为是在windows环境下运行,所以IOC容器中注册的就是bill

@Import()

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

    /**
     * {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}
     * or regular component classes to import.
     */
    Class<?>[] value();

}

我们这里来分析一下{@link ImportBeanDefinitionRegistrar}以这种方式来注册bean

作用:我们可以通过给@Import注解传入一个实现了ImportBeanDefinitionRegistrar的类来完成注册bean

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    /**
     * AnnotationMetadata: 当前标注@Import注解类的所有注解信息
     * BeanDefinitionRegistry: BeanDefinition注册类
     * @param importingClassMetadata
     * @param registry
     */
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition("person",new RootBeanDefinition(Person.class));
    }
}

FactroyBean

作用:我们可以创建一个实现FactoryBean接口的工厂类,并且实现其中的方法,从而完成bean的注册

PersonFactoryBean工厂类

public class PersonFactoryBean implements FactoryBean {
    //返回一个Person对象并且添加到容器当中
    public Object getObject() throws Exception {
        return new Person();
    }
    //返回bean对象的类型
    public Class<?> getObjectType() {
        return Person.class;
    }
    //创建的bean对象是否单例?
    public boolean isSingleton() {
        return false;
    }
}

在MyConfig中配置PersonFactoryBean

@Bean
public PersonFactoryBean personFactoryBean(){
    return new PersonFactoryBean();
}

测试类

@Test
    public void testPersonFactoryBean(){
        Object bean1 = applicationContext.getBean("personFactoryBean");
        System.out.println(bean1.getClass());
        Object bean2 = applicationContext.getBean("&personFactoryBean");
        System.out.println(bean2.getClass());
    }
    /**
     * 通过测试我们发现当我们从IOC容器中获取personFactroyBean对象时,得到的是我们通过
     * PersonFactroyBean中的 getObject()方法创建的Person对象
     *
     * 如果想要获取到PersonFactoryBean对象的话就要在name属性前加上&
     */

spring组件注册的更多相关文章

  1. 【spring 注解驱动开发】spring组件注册

    尚学堂spring 注解驱动开发学习笔记之 - 组件注册 组件注册 1.@Configuration&@Bean给容器中注册组件 2.@ComponentScan-自动扫描组件&指定扫 ...

  2. spring 组件注册

    一.声明配置类和注册 bean /** * 配置类 == applicationContext.xml 配置文件 * @author Administrator * */ //@Configurati ...

  3. Spring 注解原理(一)组件注册

    Spring 注解原理(一)组件注册 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 当我们需要使用 Spring 提供的 ...

  4. spring注解扫描组件注册

    最近对单点系统进行微服务拆分,被各个springboot的组件注册搞得云里雾里的.(有的是通过springboot的自动配置进IOC容器的,有的是自己添加构造方法添加进IOC容器.)决定抽时间将spr ...

  5. Spring注解开发-全面解析常用注解使用方法之组件注册

    目录 1. @Configuration 2. @ComponentScan excludeFilters includeFilters 使用自定义TypeFilter 3. @Bean @Scope ...

  6. Spring Framework 组件注册 之 @Import

    Spring Framework 组件注册 之 @Import 写在前面 向spring中注册组件或者叫javaBean是使用spring的功能的前提条件.而且spring也提供了很多种方式,让我们可 ...

  7. Spring Framework 组件注册 之 @Component

    Spring Framework 组件注册 之 @Component 写在前面 在spring大行其道的今天,对于spring的使用和掌握乃是不可缺少的必备技能.但是spring的整个体系尤为庞大,对 ...

  8. Spring Framework 组件注册 之 FactoryBean

    Spring Framework 组件注册 之 FactoryBean 前言 前两篇文章介绍了如何使用@Component,@Import注解来向spring容器中注册组件(javaBean),本文将 ...

  9. Spring注解开发系列Ⅰ--- 组件注册(上)

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...

随机推荐

  1. 同时启动多个tomcat,端口修改

    所用Tomcat服务器都为zip 版,非安装版.以 tomcat8 为例: 安装第二个Tomcat完成后,打开 tomcat/conf/server.xml 文件,查找以下三处: 1. 修改http访 ...

  2. 单元测试python unittest

    记录自己学习单元测试框架的一篇博客 菜鸟的学习之路比较艰辛到处找资料一把辛酸泪啊 1.首先是创建一个类里面设计一些简单的函数方便写用例: 原谅我蹩脚的英文直接用拼音命名了 : 2.接着就是创建用例文件 ...

  3. HTML5 Device Access (设备访问)

    camera api (含图片预览) 参考地址 主要为利用input type=file, accept="image/*" 进行处理 图片预览方式(两种) const file ...

  4. Statement和PreparedStatement

    Statement与PreparedStatement的关系和区别: 关系:PreparedStatement继承自Statement,都是接口. 区别:PreparedStatement可以使用占位 ...

  5. Stream和方法引用

    1.Stream流 1.for循环带来的弊端 在jdk8中,lambda专注于做什么,而不是怎么做 for循环的语法就是怎么做 for循环的循环体才是做什么 遍历是指每一个元素逐一进行处理,而并不是从 ...

  6. Android lifecycle 使用详解

    版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/gdutxiaoxu/article/det ...

  7. SpringMVC源码分析3:DispatcherServlet的初始化与请求转发

    在我们第一次学Servlet编程,学java web的时候,还没有那么多框架.我们开发一个简单的功能要做的事情很简单,就是继承HttpServlet,根据需要重写一下doGet,doPost方法,跳转 ...

  8. count(*) count(1) count(column)的区别

    count(1)中的1并不是指第一个column: count(*)和count(1)一样,包括对值为NULL的统计: count(column)不包括对值为NULL的统计,这里的column指的不是 ...

  9. python 35 多线程

    目录 多线程 1. 线程 2. 线程vs进程 3. 开启线程的两种方法. 4. 线程的特性 5. 线程的相关方法 6. join 阻塞 7. 守护线程 daemon 8. 互斥锁 多线程 1. 线程 ...

  10. 马蜂窝视频编辑框架设计及在 iOS 端的业务实践

    (马蜂窝技术公众号原创内容,ID: mfwtech) 熟悉马蜂窝的朋友一定知道,点击马蜂窝 App 首页的发布按钮,会发现发布的内容已经被简化成「图文」或者「视频」. 长期以来,游记.问答.攻略等图文 ...