Spring作为一个java程序员不可绕的过优秀框架,我们应该向掌握JDk一样掌握Spring。
作为认识Spring开始,那就从Spring HelloWorld开始
首先来引入相应的jar,虽然现在基本都使用Maven作为jar包的管理,但是为了更好了解学习Spring,我这里采用手动导入jar包方式。为了方便下载可以在http://repo.springsource.org/libs-release-local/org/springframework/spring/此地址下载相应版本,这里我用的版本是5.06
首先导入Spring所需要的4个基础jar包,以及一个loging依赖jiar包
commons-logging-1.2.jarspring-beans-5.0.6.RELEASE.jar
spring-context-5.0.6.RELEASE.jar
spring-core-5.0.6.RELEASE.jar
spring-expression-5.0.6.RELEASE.jar
首先创建一个HelloWorld类
package com.kk.spring.beans; public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public void hell(){ System.out.println("hello: "+name); } }
然后创建一个spring的配置文件,名为applicaContext.xml放在src目录下,配置如下内容
这里我推荐使用spring tools suite 的插件来方便的完成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" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd"> <!-- 配置bean class: bean的全类名,通过反射的方式在IOC容器中创建bean,所以要求Bean中有无参构造方法 id : 标识容器中的Bean,id 唯一 --> <bean id="helloWorld" class="com.kk.spring.beans.HelloWorld"> <property name="name" value="Spring...."></property> </bean> </beans>
这样就配置好了Spring,也就是把HelloWorld这个类交给了Spring管理,使用时不像以前那样new出来而是从Spring容器里取出来直接使用。
接下写一个测试类看看效果
package com.kk.spring.beans; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class test { public static void main(String[] args) { //1.创建Spring的IOC容器对象 //ApplicationConText 代表IOC容器 //ClassPathXmlApplicationContext是ApplicationConText接口的实现类,该实现类从类路劲下来加载配置文件 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicaContext.xml"); //2.从IOC容器中获取Bean实例 //用id定位到IOC容器中的Bean HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld"); //用类型返回IOC容器中的Bean,但是要求IOC容器中必须只能有一个该类型的Bean //HelloWorld helloWorld = ctx.getBean(HelloWorld.class); System.out.println(helloWorld); //3.调用hell方法 helloWorld.hell(); } }
细节:Spring容器给HelloWorld的name属性设置值时是使用的set方法把值注入如果把HelloWorld中的set方法改名Spring容器会报错,当然还有其他方法来给属性设值如构造方法等