您的位置:首页 > 编程语言 > Java开发

Spring开发环境配置以及入门案例

2016-07-18 20:28 531 查看
  之前尝试看过一次Spring,但是看得时候发现的先了解一下其他方面的知识,苦于没人指导,自己就各种百度,后面大致觉得应该这样,有了Java基础后,先去了解下Html,然后去看Servlet,然后JSP,当然数据库这个东西是必须会的~然后就可以看Struts2,或者hibernate了。

  本人用的是MyEclipse2015 + Spring4.3.1  之前去官网找了下载链接一直找不到,百度的时候get到链接一枚,http://repo.springsource.org/libs-release-local/org/springframework/spring/ 可以根据自己的需求进行下载。

手动配置

1. 下载Spring所需要的包,其所用jar包,在所下载的 spring-framework-4.3.1.RELEASE-dist   》》 libs中。

2. 在MyEclipse中新建一个Java项目,项目名为:SpringTest_01,然后选中项目,右键Build Path —>configure

build path..点开如下图所示:



添加核心包,其中commons-logging-1.2.jar包是Apache为“所有的Java日志实现”提供一个统一的接口。下载链接:http://commons.apache.org/proper/commons-logging/download_logging.cgi

点击OK就建好工程了。

3.在src目录下新建一个Spring的xml配置文件,这里取名字叫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-3.0.xsd"> 
<bean id="helloWorld" class="com.org.testspring.HelloWorld">
<property name="name" value="YH!"/>
</bean>

<bean id="gj" class="com.org.testspring.GoodJob">
</bean>
</beans>


可以看到,这里配置了两个bean,id不能重复,class对应的是工程里面的类,property name与类中构造函数对应(需保持一致才行)

类如下所示:

HelloWorld.java

package com.org.testspring;

public class HelloWorld {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void printMsg(){
System.out.println("Hello:"+name);
}
}
GoodJob.java

package com.org.testspring;

public class GoodJob {
public void printMsg(){
System.out.println("GoodJob");
}
}
最后测试的类Main.java

package com.org.testspring;

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

public class Main {

public static void main(String[]args){
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

obj.printMsg();

GoodJob gj = (GoodJob) context.getBean("gj");
gj.printMsg();
}
}


Main中获取Beans.xml,然后通过getBean调用bean.

输出结果为:

七月 18, 2016 8:26:20 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5197848c: startup date [Mon Jul 18 20:26:20 CST 2016]; root of context hierarchy
七月 18, 2016 8:26:20 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [Beans.xml]
Hello:YH!
GoodJob


整个运行流程为:

1. 找到Main方法,Spring框架使用
ClassPathXmlApplicationContext
创建一个容器,

2. 这个容器从Beans.xml中读取配置信息,并根据配置信息来创建bean对象,每个bean有唯一id

3.通过context.getBean()找到这个id对应的bean,获取对象的引用

4.通过对象的引用调用相应的方法。

第一个测试搞定,后续路漫漫,,,吾...........继续努力好了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: