Spring学习笔记(一)

1、官网下载Spring3.2:http://www.springsource.org/download/community

2、Spring编译和运行所依赖的第三方类库需要单独下载

3、引入Spring包中dist下的所有jar包以及依赖包下的common-logging jar包。

4、第一个例子,建立一个User类:

package com.sxit.service;

public class User {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void info(){
		System.out.println("My Name is :"+name);
	}
}

 5、在src根目录下写一个Bean.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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:oscache="http://www.springmodules.org/schema/oscache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springmodules.org/schema/oscache http://www.springmodules.org/schema/cache/springmodules-oscache.xsd">

	<bean id="UserService" class="com.sxit.service.User">
		<property name="name" value="sb" />
	</bean>

</beans>

 6、写一个测试类:

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sxit.service.User;

public class Test {

	public static void main(String[] args) {
		
		//ApplicationContext实例是spring容器,但它只是个接口,ClassPathXmlApplicationContext是它的具体实现类
		ApplicationContext apc = new ClassPathXmlApplicationContext("Bean.xml");
		System.out.println("容器是:"+apc);
		
		User user = apc.getBean("UserService", User.class);
		user.info();
	}
}

7、打印的内容:

容器是:org.springframework.context.support.ClassPathXmlApplicationContext@c1b531: startup date [Mon Nov 05 12:36:58 GMT 2012]; root of context hierarchy
My Name is :sb

 8、总结:

1)、ApplicationContext实例是Spring容器,一旦获得Spring容器就可以管理容器中声明的Bean。
2)、ClassPathXmlApplicationContext只是其中一个实现类,还可以通过FileSystemXmlApplicationContext来实例化容器
ApplicationContext apc = new FileSystemXmlApplicationContext("classpath:Bean.xml");
ApplicationContext apc = new FileSystemXmlApplicationContext("src/Bean.xml");
3)、通过代码可以看出,Test类中没有创建User对象,而是通过Spring容器获取到User的实例,并且该对象的属性name已经被赋值为'sb',这种Spring通过配置文件信息来创建对象并设置属性的方式被称为控制反转。

 

你可能感兴趣的:(spring)