day118 - 基于xml管理bean的入门案例
入门案例
导入依赖
<dependencies> <!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.1</version> </dependency> <!-- junit测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
创建helloworld
package com.gu.spring.pojo; public class HelloWorld { public void sayHello(){ System.out.println("hello spring"); } }
配置spring
<!-- bean: 将对象交给ioc容器管理 属性: id:bean得唯一标识,不能重复 class:设置bean对象所对应的类型 --> <bean id="helloworld" class="com.gu.spring.pojo.HelloWorld"></bean>
测试类
@Test public void test(){ //获取ioc容器 ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取ioc容器中的bean对象 HelloWorld helloworld = (HelloWorld) ioc.getBean("helloworld"); helloworld.sayHello(); }
总结
通过测试类中创建ioc的容器对象,读取spring中的配置文件,文件中指定了自定义的组件类,ioc容器调用组件创建对象。
注意
Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name'helloworld' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception isorg.springframework.beans.BeanInstantiationException: Failedto instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nestedexception is java.lang.NoSuchMethodException:com.atguigu.spring.bean.HelloWorld.()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY