Java框架之Spring(二)
前一篇博客讲述了Spring的一些基础概念,下面我们来创建第一个Spring程序吧。
步骤如下:
1) 导包
2) 配置文件
附没有提示的情况
MyEclipse ->File and Editors -XML ->XML Catlog, 点击 add,找到上面的文件 spring-beans-3.1.xsd,然后 Key type 选 SchemaLoaction, key 后面加上 spring-beans-3.1.xsd即可。
//beans.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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> //这里自己根据需要去设置,将UserInf这个类交给Spring管理 <bean name="userInfo_name" class="cat.beans.UserInfo" > <property name="id" value="1" /> <property name="userName" value="赵明明" /> <property name="password" value="123" /> <property name="note" value="这是备注" /> </bean> </beans>
public class Test { public static void main(String[] args) { //初始化容器 ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml"); UserInfo user=(UserInfo) ctx.getBean("userInfo_name");//下面讲解两种等效方法 /*可以这样,条件是在beans.xml中只有一个userInfo_name的情况下。 *多了,就不能用这个了,因此推出可以用下面带参数的方法 *UserInfo user=ctx.getBean(UserInfo.class); */ //带参数的方法 //UserInfo user=ctx.getBean("userInfo_name", UserInfo.class); System.out.println(user); /*附加:初始化容器,也可以这样写 *ApplicationContext ctx= new ClassPathXmlApplicationContext("beans.xml"); *因为 ApplicationContext 是 ClassPathXmlApplicationContext的父类 */ } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程