【SpringBoot】Bean的多种加载方式

SpringBoot中注册Bean的十种方式

定义一个需要被注册为Bean的类或接口

public class Introduction {
    private String name;
    private String introduce;
    private int id;
}

XML方式注册Bean

resource文件夹下新建一个xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="introduction" class="com.example.learn.Introduction" >
        <property name="name" value="XXX"></property>
        <property name="introduce"  value="XXXXX"></property>
        <property name="id" value="0"></property>
    </bean>
</beans>

然后在入口处添加注释:

@ImportResource("Introduction.xml")

基于注解方式注册Bean (自定义类)

在类定义的上方添加以下注解都可以将其注册为bean,只是不同的注解应用的地方不同

@Component

@Repository

@Service

@Controller

配合上面的注解,需要写一个xml配置文件定义组件扫描的路径

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           https://www.springframework.org/schema/context/spring-context.xsd">

       <context:component-scan base-package="com.example.learn"/>
</beans>

基于注解方式注册Bean (第三方类)

注入第三方Bean需要使用到@Bean注解,bean的name属性与方法名一致
这里需要注意的是,用@Bean注解定义的方法,其所在的类也需要注册为Bean

@Data
@Component("introduction")
public class Introduction {
    private String name;
    private String introduce;
    private int id;
    
    
    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource ds =new DruidDataSource();
        return ds;
    }
}

基于配置类注册Bean

通过配置类替代xml文件,在上述两种基于注解注册Bean的基础上,添加以下配置类

@ComponentScan({"com.example.learn"})
public class Config {
}

可以不用为此配置类添加**@Configuration注解
@Configuration注解中有一个
proxyBeanMethods**属性,设置为True时,@Bean注册的bean为单例模式,反之每次重新创建。

工厂Bean方式注册Bean

使用工程Bean注册Bean需要实现FactoryBean这一接口
最终注册Bean的方式是基于@Bean注解在一个方法上实现

public class IntroductionFactoryBean implements FactoryBean<Introduction> {

    /**
     * 定义返回的对象
     * @return
     * @throws Exception
     */
    @Override
    public Introduction getObject() throws Exception {
        return new Introduction();
    }

    /**
     * 定义返回的对象类型,如果泛型是一个接口,那么可以返回实现类的类型
     * @return
     */
    @Override
    public Class<?> getObjectType() {
        return Introduction.class;
    }
    
    /**
     * 定义是否为单例模式
     * @return
     */
    @Override
    public boolean isSingleton() {
        return FactoryBean.super.isSingleton();
    }
}

@Import注解方式注册Bean

首先再新建一个自定义类作为辅助

public class IntroductionTest {
}

使用@Impot注解将IntroductionTest 注入

@Import(IntroductionTest.class)
@Component("introduction")
public class Introduction {
    private String name;
    private String introduce;
    private int id;

    @Bean
    public DruidDataSource getDataSource(){
        DruidDataSource ds =new DruidDataSource();
        return ds;
    }
}

上下文加载成功后注册Bean

使用registerBean()方法注册Bean

public class LearnApplication {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
		ctx.registerBean("introductionTest", IntroductionTest.class);
	}
}

基于ImportSelector接口注册Bean

在接口中的AnnotationMetadata 类的对象 importingClassMetadata中包含导入该MyImportSelector的类的源信息,可以判断是否含有注解,方法等。
然后根据各种条件添加下面的定义的bean

public class MyImportSelector implements ImportSelector {

    /**
     * 在返回的字符串数组中给定需要注册为bean的类的全路径类名
     * @param importingClassMetadata
     * @return
     */
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        
        String[] beans = {"com.example.learn.Introduction"};
        return beans;
    }
}

基于ImportBeanDefinitionRegistrar接口注册Bean

在添加条件筛选的基础上,使用BeanDefinitionRegistry去注册bean

public class MyBeanRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        BeanDefinition bd = BeanDefinitionBuilder.rootBeanDefinition(Introduction.class).getBeanDefinition();
        registry.registerBeanDefinition("introduce", bd);
    }
}

基于BeanDefinitionRegistryPostProcessor接口注册Bean

作为一个后处理Bean注册类,其具有最后注册bean的权限

public class MyPostProcess implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        BeanDefinition bd = BeanDefinitionBuilder.rootBeanDefinition(Introduction.class).getBeanDefinition();
        beanDefinitionRegistry.registerBeanDefinition("introduce", bd);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值