初识Spring
1)首先对于框架的学习,就是要搭建环境
第一步:建一个Java Project
需要的 jar 包 commons-logging-1.1.3.jar 和 spring-2.5.4.jar
在Java Project下建立一个 lib 目录
将上面的 jar 包拷入lib目录下
第二部:在 src 下建一个 beans.xml 文件
在 spring-framework-4.0.2.RELEASE\docs\spring-framework-reference\htmlsingle
找到index.html打开
找到下面文件

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <bean id="..." class="..."> 8 <!-- collaborators and configuration for this bean go here --> 9 </bean> 10 11 <bean id="..." class="..."> 12 <!-- collaborators and configuration for this bean go here --> 13 </bean> 14 15 <!-- more bean definitions go here --> 16 17 </beans>
将其复制到建好的beans.xml文件中
第三部:关联
http://www.springframework.org/schema/beans/spring-beans.xsd
如图关联:
第四部:编辑第一个Spring(比较简单)
1)class---(PersonServiceBean.java)

1 package com.baidu.service.impl; 2 3 import com.miao.service.PersonService; 4 5 public class PersonServiceBean implements PersonService { 6 7 @Override 8 public void save() { 9 System.out.println("save..."); 10 } 11 }
2)interface---(PersonService.java)

1 package com.miao.service; 2 3 public interface PersonService { 4 5 public abstract void save(); 6 7 }
3)xml---(beans.xml)

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <bean id = "personService" class = "com.baidu.service.impl.PersonServiceBean"></bean> 7 </beans>
4)单元测试类---(SpringTest.java)

1 package spring; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 import org.springframework.context.ApplicationContext; 7 import org.springframework.context.support.ClassPathXmlApplicationContext; 8 9 import com.miao.service.PersonService; 10 11 public class SpringTest { 12 13 14 @Test 15 public void instanceSpring() { 16 //在类路径下寻找配置文件,来实例化容器 17 ApplicationContext atc = new ClassPathXmlApplicationContext( 18 new String[] { "beans.xml" }); 19 20 // 通过接口对其进行应用 21 PersonService personService = (PersonService) atc 22 .getBean("personService"); 23 //调用接口的方法 24 personService.save(); 25 26 } 27 28 }
参考目录结构:
好了第一个Spring程序写好了---
总结:
实例化spring容器
面向接口编程
解释:Spring中实例化spring容器中----"new String[]"--表示可以传入多个的配置文件
本人是一个Java爱好者,欢迎交流 ^_^
------By 小苗
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步