当前位置: 首页 > news >正文

在Spring框架中创建Bean实例的几种方法

我们希望Spring框架帮忙管理Bean实例,以便得到框架所带来的种种功能,例如依赖注入等。将一个类纳入Spring容器管理的方式有几种,它们可以解决在不同场景下创建实例的需求。

  • 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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean name="testService" class="com.example.demo.test.TestService"/>
    </beans>
    
    • 需要指定配置文件来初始化Spring容器ApplicationContext context = new ClassPathXmlApplicationContext("services.xml");
    • 这种方式已经过时了,在历史项目中可能还有身影。
    • 在配置文件中还可对实例化过程进行一些调整,例如可延迟到实例使用时才真正初始化(延时加载)、实例作用域等。
  • 在目标类头上加注解

    import org.springframework.stereotype.Service;
    @Service
    public class TestService {
    }
    
    • 目前大家普遍使用Spring boot,可以很方便地在目标类上加注解,框架使用AnnotationConfigApplicationContext扫描类识别到注解后,将类进行初始化。默认只会扫描启动类的包目录,你可以通过@ComponentScan来配置其它包路径。
    • 那么使用哪些类才会被扫描到呢?
      • 只要该注解类中有增加org.springframework.stereotype.Component元注解,像上面的@Service注解类头上就有。
      • 常见的有@ControllerAdvice、@Configuration、@Controller、@Repository、@Service、@Autowired、@Resource和@Component等。
  • 通过编程方式

    @Configuration
    public class TestConfiguration {@Beanpublic TestService getTestService() {return new TestService();}
    }
    
    • 这种方式可以让开发者更容易的控制Bean实例化过程,例如可以从外部来源获取参数,最终将类实例化。
  • 获取ApplicationContext来构建

    public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(AppStater.class, args);BeanDefinitionBuilder bdf = BeanDefinitionBuilder.genericBeanDefinition(TestService.class);((DefaultListableBeanFactory) context.getAutowireCapableBeanFactory()).registerBeanDefinition("testService", bdf.getBeanDefinition());
    }
    
    • 这种方式需要注意使用Bean的时机,因为在Spring容器初始时并没有创建它,所以这种方式也可以实现动态加载Bean。
    • 在实现类似插件这种机制时,必不可少的就是动态加载,在程序启动时并不知道将会实例化什么类,等到运行过程中通过配置或其它外部源动态获取要实例化的类。
  • 为了获取Spring容器,一般会创建一个工具类,方便开发者在代码任意位置就能拿到容器,下面代码可以拿走即用。

    package cn.com.example.app.commons.spring;import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.DisposableBean;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.annotation.Lazy;
    import org.springframework.stereotype.Component;
    import org.springframework.util.Assert;/*** 以静态变量保存 Spring ApplicationContext,可在任何代码任何地方任何时候取出ApplicationContext。** @author tianmingxing <mx.tian@qq.com>* @date 2022-03-08*/
    @Component
    @Lazy(value = false)
    public class SpringContextHolder implements ApplicationContextAware, DisposableBean {public static ApplicationContext ctx = null;@SuppressWarnings("unchecked")public static <T> T getBean(String name) {assertContextInjected();return (T) ctx.getBean(name);}public static <T> T getBean(Class<T> clazz) {assertContextInjected();return ctx.getBean(clazz);}public static ApplicationContext getContext() {assertContextInjected();return ctx;}@Overridepublic void destroy() throws Exception {ctx = null;}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {ctx = applicationContext;}
    }
    
  • 除此之外还有一些方法,采用框架的一些特性,在过程中顺便完成实例初始化,算是被动的做了这件事情。

http://www.lryc.cn/news/9701.html

相关文章:

  • PyQt5 界面预览工具
  • day44【代码随想录】动态规划之零钱兑换II、组合总和 Ⅳ、零钱兑换
  • 计算机网络第1章(概述)学习笔记
  • GPT-3(Language Models are Few-shot Learners)简介
  • 容器安全风险and容器逃逸漏洞实践
  • 2023年美赛B题-重新想象马赛马拉
  • Docker常用命令总结
  • mac环境,安装NMP遇到的问题
  • Web Worker 与 SharedWorker 的介绍和使用
  • React:Redux和Flux
  • TypeScript 学习之Class
  • doris - 数仓 拉链表 按天全量打宽表性能优化
  • 服务器虚拟化及优势
  • 华为ensp模拟校园网/企业网实例(同城灾备及异地备份中心保证网络安全)
  • git命令篇(持续更新中)
  • 用记事本实现“HelloWorld”输出
  • Python基础1
  • 4.2 双点双向路由重发布
  • AcWing《蓝桥杯集训·每日一题》—— 3768 字符串删减
  • 第五天笔记
  • 如何使用ArcGIS进行地理配准
  • 【java基础知识】
  • Java提供了哪些IO方式? NIO如何实现多路复用?
  • 人的大脑遇事的思考解决过程
  • GNU zlib 压缩与解压文件详细介绍
  • 离线环境轻量级自动化部署
  • In-context Learning
  • 【新2023】华为OD机试 - 最优调度策略(Python)
  • Python列表系列之统计计算
  • 【蓝桥杯集训·每日一题】AcWing 1460. 我在哪?