spring框架学习

Spring是一个类的容器实例化托管框架,可以实现对实现类的实例化进行动态的托管。更可以实现控制反转。控制

反转就是应用本身不负责倚赖对象的创建和维护,倚赖对象的创建和维护是通过其他的外部容器负责的,这样的控制

权就由应用转移到了容器。控制权的转移就是所谓的反转。


下面我们来说一下一个简单的Spring框架的搭建和实例.首先下载下来spring的压缩包,在解压后的dist文件夹下

面有spring.jar和commons-logging.jar这两个JAR包,这就是实现最简单的spring框架所必须的包,然后就是

在docs/reference下面的参考手册,里面有spring的配置文件写法。导入包完成后,最好在src目录下面建立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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	
	<bean id="personService" class="com.bird.service.impl.PersonServerImpl"></bean>
</beans>



然后写一个类和抽取出接口
package com.bird.service;

public interface PersonServer {

	void save();

}

package com.bird.service.impl;

import com.bird.service.PersonServer;

public class PersonServerImpl implements PersonServer {
	
	@Override
	public void save(){
		System.out.println("save()方法调用");
	}
}
 


然后在beans.xml中配置这个类就可以使用spring实例化这个类了,下面的操作全部都是面向接口的编程了。
package junit.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bird.service.PersonServer;

public class SpringTest {
	
	@Test
	public void test(){
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonServer s = (PersonServer)ctx.getBean("personService");
		s.save();
	}                                                                                                                                                                                                                                                              
}

你可能感兴趣的:(spring)