【Spring】初始化Spring IoC容器(非Web应用),并获取Bean
参考文章
Introduction to the Spring IoC container and beans
BeanFactory 和ApplicationContext(Bean工厂和应用上下文)
Spring ApplicationContext - Resource leak: 'context' is never closed
版本说明
- JDK 1.7
- Spring3.2.14

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.14.RELEASE</version> </dependency>
Java项目中,启动Spring IoC、获取Bean
CLASS PATH下放一个最简单的Spring配置文件
<?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-3.0.xsd"> <bean id="demoBean" class="com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean"> </bean> </beans>
需要由Spring托管的Bean Class
package com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean; public class DemoBean { public String test() { return "hello spring..."; } }
调用类
package com.nicchagil.springapplication.No001initSpringIocAndGetABean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean; public class Call { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); DemoBean d1 = context.getBean("demoBean", DemoBean.class); DemoBean d2 = context.getBean("demoBean", DemoBean.class); /* execu the method*/ System.out.println(d1.test()); System.out.println(d2.test()); /* default singleton */ System.out.println("demoBean isSingleton ? -> " + context.isSingleton("demoBean")); System.out.println(d1); System.out.println(d2); System.out.println("d1 == d2 -> " + (d1 == d2)); } }
日志
hello spring... hello spring... demoBean isSingleton ? -> true com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean@4857b188 com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean@4857b188 d1 == d2 -> true
作者:Nick Huang 博客:http://www.cnblogs.com/nick-huang/
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
分类:
Spring
标签:
Spring framework
, Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用