从本篇博客开始,后续将重点学习Spring,并记录学习过程中的点点滴滴。
开发环境:jdk 1.7,Eclipse Mars, Spring Framwork 4.3.0
1、 在Eclipse中创建自己的依赖Jar包库
在进行spring开发时,spring框架提供的许多依赖包,在每次新建一个Project后,均需要将这些依赖包导入工程中。Eclipse提供了一个很方便的功能:创建user library,将spring开发需要的依赖包全部放入自定义的user library中。
步骤如下:
(1)点击eclipse的window菜单,选择“Preferences”;
(2)在Preferences中选择Java->Bulid Path->User Libraries,然后点击窗口右边的New按钮,在弹出的子窗口中输入user library的名称,比如spring;
(3)点击Add External JARs,弹出窗口,将spring框架的依赖包添加进去。
创建好用户依赖库spring后,下面介绍如何创建spring的入门示例。
2、Spring的入门示例
先直接给出Spring的一个简单工程实例,下一篇博客再重点介绍Spring的框架。
新建一个mavean工程,工程目录结构为:
导入user library spring依赖库
右键Project名称->Build Path ->Add Libraries..,选择User Library,就会看到spring库
创建HelloWorld类
package com.wygu.spring_hello;
public class HelloWorld {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printHello() {
System.out.println("Welcome Spring 4.3.0 !! " + this.getName()+":"+this.getAge());
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
定义XML配置文件applicationContext.xml,放置在xml文件夹中
<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-4.3.xsd">
<bean id="helloBean" class="com.wygu.spring_hello.HelloWorld">
<property name="name" value="wygu" />
<property name="age" value="17" />
</bean>
</beans>
创建运行类APP
package com.wygu.spring_hello;
/**
* Hello world!
*
*/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class APP {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHello();
}
}
如果直接运行会报错:
原因是由于在类APP中加载不到applicationContext.xml
解决方法:
右击xml,选择Build Path->Use as Source Folder
工程运行结果为:
Welcome Spring 4.3.0 !! wygu:17