zoukankan      html  css  js  c++  java
  • Spring注解创建Bean的几种方式

    Spring注解创建Bean的几种方式

    1、@Component系列

    @Component
    @Service
    @Repository
    @Controller
    @Configuration
    

    2、 依附于@Configuration的注解 

    @Bean 创建Deom

    @Configuration
    public class Demo {
        @Bean
        public Demo demo(){
            return new Demo();
        }
    }
    

    @Import  创建Cofing

    @Configuration
    @Import(Config.class)
    public class Demo {
       
    }
    

    @Import.ImportSelector 选择器,传入@Import注解所在类Demo上所有的注解信息,返回要导入的类名

    @Configuration
    @Import(ImportSelector_.class)
    public class Demo {   
    }
    public class ImportSelector_ implements ImportSelector {
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            return new String[]{"com.spring.demo.beanlifecycle.Demo"};
        }
    }
    

    @Impport.ImportBeanDefinitionRegistrar  Bean定义注册器,传入@Import注解所在类Demo上所有的注解信息(1),Bean定义注册器(2)

    //PS:Mybatis的Mapper接口就是用这种方式将Bean定义注册到Spring上下文的

    @Configuration
    @Import(ImportBeanDefinitionRegistrar_.class)
    public class Demo {
    }
    public class ImportBeanDefinitionRegistrar_ implements ImportBeanDefinitionRegistrar {
        @Override
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Bean.class).setInitMethodName("init").setDestroyMethodName("destroy").getBeanDefinition();
            registry.registerBeanDefinition("bean", beanDefinition);
            System.out.println("registerBeanDefinitions: " + beanDefinition);
        }
    }
    

     

    3、FactoryBean  

    当通过“factoryBean”获取实例时,FactoryBean会调用getObject()方法

    当通过“&factoryBean”获取实例时,返回FactoryBean的实例

    当通过Demo.class来获取bean实例时,调用factoryBean的getObjectTyoe()来获取类型。

    @Configuration
    public class Demo {
        @Bean
        public FactoryBean_ factoryBean(){
            return new FactoryBean_();
        }
    }
    public class FactoryBean_ implements FactoryBean {
        @Override
        public Object getObject() throws Exception {
            return new Demo();
        }
        @Override
        public Class<?> getObjectType() {
            return Demo.class;
        }
    }
    

      

  • 相关阅读:
    对于高并发短连接造成Cannot assign requested address解决方法
    virtualbox迁移已建虚机存储磁盘方法
    httpd:RSA certificate configured for SERVER does NOT include an ID which matches the server name
    解决服务不断重启挂掉问题
    tbb静态库编译
    su和su
    ubuntu18.04 mariadb start失败
    如何修复“sshd error: could not load host key”
    [LeetCode]Gas Station
    Java多态的一些陷阱
  • 原文地址:https://www.cnblogs.com/sleepingDogs/p/11104916.html
Copyright © 2011-2022 走看看