Spring框架环境搭建

如何在Eclipse中对Spring框架进行环境搭建

1.导入核心jar包。这里我使用的是4.1.6的版本,一共是四个核心包加一个日志包(commons-logging)

2.在项目的src下新建一个applicationContext.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.xsd">
    <!-- id表示获取到对象标识
    	 class 创建哪个类的对象
     -->
    <bean id="peo" class="a.b.pojo.People"/>
</beans>

3.编写一个测试方法

实体类

package a.b.pojo;

public class People {
	private int id;
	private String name;
	
	
	public People() {
		super();
		System.out.println("执行构造方法");
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "People [id=" + id + ", name=" + name + "]";
	}
}

测试方法

package a.b.test;

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

import a.b.pojo.People;

public class Test {
	public static void main(String[] args) {
//		People peo = new People();
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		People people = ac.getBean("peo",People.class);
		System.out.println(people);
		
//		String[] names = ac.getBeanDefinitionNames();
//		for (String string : names) {
//			System.out.println(string);
//		}
	}
}

其实在Spring容器中applicationContext.xml文件配置的信息最终存储到了ApplicationContext容器中。Spring的配置文件是基于schema的,它是一个.xsd文件,也可以把它理解为DTD的升级版。它比DTD具备更好的扩展性,每次引入一个xsd文件就相当于是一个namespace(xmlns)。在配置文件中只需要引入基本的schema,通过<bean/>来创建对象,默认配置文件就会被加载时创建对象,详细可以看第一步的代码。

以上就是完成了Spring框架的环境基本搭建,当然我们还可以在核心配置文件中添加更多的内容,接下来我会在之后的博客中继续讲解




猜你喜欢

转载自blog.csdn.net/let_me/article/details/80991948