1、方式一:基于spring.xml方式配置Bean

user
import lombok.Data;

/**
* @author : ly
*/
@Data
public class User { private String name;
private Integer age; }
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="user1" class="com.ly.domain.User">
<property name="name" value="张三"/>
<property name="age" value="25"/>
</bean> </beans>
test
/**
* @author : ly
*/
@SpringBootTest
public class GetBeanTest { private ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml"); @Test
public void testXML(){
User user1 = app.getBean("user1", User.class);
System.out.println("user1 = " + user1);
} }
结果

2、方式二:基于properties方式配置Bean

properties
user.(class) = com.ly.domain.User
user.name = 李四
user.age = 20
test
@Test
public void testProperties(){
GenericApplicationContext applicationContext = new GenericApplicationContext();
//创建一个PropertiesBeanDefinitionReader,可以从properties读取Bean的信息,将读到的Bean信息放到applicationContext中
PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(applicationContext);
//创建一个properties文件对应的Resource对象
Resource classPathResource = new ClassPathResource("bean1.properties");
//加载配置文件
propReader.loadBeanDefinitions(classPathResource);
applicationContext.refresh();
User user = applicationContext.getBean(User.class);
System.out.println(user);
}
结果

3、方式三:@Component + @ComponentScan,衍生注解@Controller、@Service、@Repository...

这种方式常用,而且不叫简单就不写案例了

4、方式四:@Bean针对第三方的Bean

例如我们配置MybatisPlus分页插件时,就是使用@Bean方式把分页插件MybatisPlusInterceptor交给Spring管理

@Bean
@Configuration
public class MybatisPlusConfig { //分页拦截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInterceptor.setMaxLimit(500L);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setDbType(DbType.MYSQL); interceptor.addInnerInterceptor(paginationInterceptor);//分页
return interceptor;
} }

5、方式五:@Import|@ImportSelector|@ImportBeanDefinitionRegistrar导入对应的Bean

@Import

通过import的方式将bean加入到spring容器中,这些在容器中bean名称是该类的全类名 ,比如com.ly.User

test
@Import(User.class)

@ImportSelector

UserImportSelector
/**
* @author : ly
*/
@Slf4j
public class UserImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
log.info("通过ImportSelector导入对应的Bean");
return new String[]{"com.ly.domain.Dog"};
}
}
MyImportSelector
/**
* @author : ly
*/
@Import(UserImportSelector.class)
public class MyImportSelector { }
test
@Test
public void testImportSelector(){
Dog dog = ctx.getBean(Dog.class);
System.out.println("dog = " + dog);
}
结果

@ImportBeanDefinitionRegistrar

UserImportBeanDefinitionRegistrar
public class UserImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
registry.registerBeanDefinition("dogRegister",new RootBeanDefinition(Dog.class));
}
}
UserImportRegisterAnnotation
/**
* @author : ly
*/
@Import(UserImportBeanDefinitionRegistrar.class)
public class UserImportRegisterAnnotation {
}
test
@Test
public void testImportRegister(){
Dog dog = ctx.getBean("dogRegister", Dog.class);
System.out.println("dog = " + dog);
}
结果

6、方式六:BeanFactoryPostProcessor注册对应的Bean

UserBeanDefinitionRegistryPostProcessor
/**
* @author : ly
*/
public class UserBeanDefinitionRegistryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
User user = new User();
user.setName("王五");
user.setAge(20);
configurableListableBeanFactory.registerSingleton("userProcessor", user);
}
}
测试
@Test
public void testProcessor(){
AnnotationConfigApplicationContext app2 = new AnnotationConfigApplicationContext();
app2.register(UserBeanDefinitionRegistryPostProcessor.class);
app2.refresh(); User userProcessor = app2.getBean("userProcessor", User.class);
System.out.println("userProcessor = " + userProcessor);
}
结果

7、方式七:FactoryBean

当我们通过配置文件、注解声明或者是注册BeanDenifition的方式,往Spring容器中注入了一个class类型为FactoryBean类型的Bean时候,其实真正注入的Bean类型为getObjectType方法返回的类型,并且Bean的对象是通过getObject方法返回的。

UserFactoryBean
/**
* @author : ly
*/
public class UserFactoryBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
User user = new User();
user.setName("赵六");
user.setAge(23);
return user;
} @Override
public Class<?> getObjectType() {
return User.class;
} @Override
public boolean isSingleton() {
return true;
}
}
test
@Test
public void testFactorBean(){
app2.register(UserFactoryBean.class);
app2.refresh(); User bean = app2.getBean(User.class);
System.out.println("bean = " + bean);
}
结果

总结:

Bean注入到Spring容器中大致可以分这么几种:

  • 配置文件
  • 注解声明
  • BeanDefinition
  • BeanFactoryPostProcessor注册Bean
  • FactoryBean

Spring中Bean的加载方式~的更多相关文章

  1. 【Spring】详解Spring中Bean的加载

    之前写过bean的解析,这篇来讲讲bean的加载,加载要比bean的解析复杂些,该文之前在小编原文中有发表过,要看原文的可以直接点击原文查看,从之前的例子开始,Spring中加载一个bean的方式: ...

  2. Vue中图片的加载方式

    一.前言 VUE项目中图片的加载是必须的,那么vue中图片的加载方式有哪些呢,今天博主就抽点时间来为大家大概地捋一捋. 二.图片的加载方法 1.在本地加载图片(静态加载) 图片存放assets文件夹中 ...

  3. Spring 容器中bean的加载过程

    bean 的加载过程大致可以分为以下几个步骤: 1.获取配置的资源文件 2.对获取到的xml资源文件进行解析 3.获取包装资源 4.解析处理包装之后的资源 5.加载 提取bean 并进行注册(添加到b ...

  4. Spring IoC bean 的加载

    前言 本系列全部基于 Spring 5.2.2.BUILD-SNAPSHOT 版本.因为 Spring 整个体系太过于庞大,所以只会进行关键部分的源码解析. 本篇文章主要介绍 Spring IoC 容 ...

  5. 如果你还不知道如何控制springboot中bean的加载顺序,那你一定要看此篇

    1.为什么需要控制加载顺序 springboot遵从约定大于配置的原则,极大程度的解决了配置繁琐的问题.在此基础上,又提供了spi机制,用spring.factories可以完成一个小组件的自动装配功 ...

  6. Spring中资源的加载原来是这么一回事啊!

    1. 简介 在JDK中 java.net.URL 适用于加载资源的类,但是 URL 的实现类都是访问网络资源的,并没有可以从类路径或者相对路径获取文件及 ServletContext , 虽然可以通过 ...

  7. 浅谈Entity Framework中的数据加载方式

    如果你还没有接触过或者根本不了解什么是Entity Framework,那么请看这里http://www.entityframeworktutorial.net/EntityFramework-Arc ...

  8. 简说Spring中的资源加载

    声明: 本文若有 任何纰漏.错误,请不吝指正!谢谢! 问题描述 遇到一个关于资源加载的问题,因此简单的记录一下,对Spring资源加载也做一个记录. 问题起因是使用了@PropertySource来进 ...

  9. Spring中的资源加载

    大家也都知道JDK的类加载器:BootStrap ClassLoader.ExtenSion ClassLoader.Application ClassLoader:也使用了双亲委派模型,主要是为了防 ...

  10. Spring中Bean的不同配置方式

    Bean的配置方式一共分为三种: 1.基于XML(适用于第三方类库,无法在类中写注解以及写命名空间的配置等情况) 2.基于注解(适用于大部分情况) 3.基于Java类 以下是三种不同情况的配置方式   ...

随机推荐

  1. AI绘画StableDiffusion:云端在线版免费使用笔记分享-Kaggle版

    玩AI绘画(SD),自己电脑配置不够?今天给大家介绍一下如何baipiao在线版AI绘画StableDiffusion. Kaggle 是世界上最大的数据科学社区,拥有强大的工具和资源,可帮助您实现数 ...

  2. 《最新出炉》系列入门篇-Python+Playwright自动化测试-15-playwright处理浏览器多窗口切换

    1.简介 浏览器多窗口的切换问题相比大家不会陌生吧,之前宏哥在java+selenium系列文章中就有介绍过.大致步骤就是:使用selenium进行浏览器的多个窗口切换测试,如果我们打开了多个网页,进 ...

  3. tarjan强连通分量

    int scc[N],sc;//结点i所在scc的编号 int sz[N]; //强连通i的大小 //dfn(u)为搜到结点u时的次序编号 //low(u)为u或u的子树能够追溯到的最早的栈中节点的次 ...

  4. Go 1.22 中的 For 循环

    原文在这里. 由 David Chase and Russ Cox 发布于2023年9月19日 Go 1.21 版本包含了对 for 循环作用域的预览更改,我们计划在 Go 1.22 中发布此更改,以 ...

  5. 算法打卡|Day1 数组part01

    Day1 数组part01 今日任务:数组理论基础,704. 二分查找,27. 移除元素 目录 Day1 数组part01 今日任务:数组理论基础,704. 二分查找,27. 移除元素 Part1: ...

  6. 两种方式,创建有返回值的DB2函数

    函数场景:路径信息由若干个机构编码组成,且一个机构编码是9位字符. 要求:获取路径信息,并且删除路径中包含'99'开头的机构编码. 从客户端及服务器端分别创建ignore99(pathinfo var ...

  7. PostgreSQL主备库搭建

    pg主备库的搭建,首先需在2个节点安装pg软件,然后依次在2个节点配置主备. 本文采用os为CentOS7.6,pg版本使用14.2,以下为详细部署步骤. 本文两个节点的ip地址如下: [root@n ...

  8. 01-spfile和pfile的区别,生成,加载和修复

    oracle数据库的配置文件指的是系统在启动到"nomount"阶段需要加载的文件,也叫做pfile或者spfile,但是其实pfile和spfile是不同的文件. 不同的数据库配 ...

  9. Iksevi 题解

    Iksevi 题目大意 \(n\) 次询问,每次给定一个点 \((x,y),x\ge 0, y\ge 0\),问有多少种对角线长为偶数的正方形使得在用该正方形正密铺第一象限的情况下该点位于正方形顶点上 ...

  10. 从零用VitePress搭建博客教程(2) –VitePress默认首页和头部导航、左侧导航配置

    2. 从零用VitePress搭建博客教程(2) –VitePress默认首页和头部导航.左侧导航配置 接上一节: 从零用VitePress搭建博客教程(1) – VitePress的安装和运行 四. ...