因为课程项目需要用到Spring框架,因此我花了两星期的时间在腾讯课堂上看在线课程学习了Spring框架,
课程链接是:
https://ke.qq.com/course/27346
https://ke.qq.com/course/27350
在接下来的博客中,我主要和大家分享一下我在学习中遇到的问题和解决的方法。
一、环境配置
开发平台:Eclipse Kepler
在Eclipse中安装Spring Tool Suite插件以便在Eclipse平台上开发基于Spring的应用
首先去下载插件:springsource-tool-suite-3.4.0.RELEASE-e4.3.1-updatasite.zip
下载链接:https://pan.baidu.com/s/1hqw11R2
然后Help->Install New Software->Add->Archive->选择安装文件路径->OK->
选择Core/Spring IDE、Extensions/Spring IDE、Integrations/Spring IDE、Resource/Spring IDE
之后一路next、accept、finish就搞定了,如果出现安装失败的情况,多半是因为插件与Eclipse版本不兼容,可以通过重装Eclipse来解决。在上面的链接中,有Eclipse Kepler的安装包。
二、写一个HelloWorld
1.最简单的开始方式是new 一个Spring Project,这样的话会自动配置好Spring框架所需要的jar包,也可以新建一个java project然后自己手动添加jar包:(commons-logging、spring-beans、spring-context、spring-core、spring-expression),又或者新建Maven Project然后在pom.xml中加入依赖信息。这都是可以的。
弄好之后的目录是下面这样的:
2.写一个HelloWorld的类,用于在控制台打印hello:***
package beans;
public class HelloWorld {
private String name;
public void setName2(String name) {
this.name = name;
}
public void hello() {
System.out.println("hello: " + name);
}
}
类中需要有对成员变量的setter方法,用于在bean配置文件中使用property属性对其进行赋值。
3.新建一个SpringBean的配置文件applicationContext.xml
New->Spring Bean Configuration File
<?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">
<!-- 配置bean -->
<bean id="helloWorld" class="beans.HelloWorld">
<property name="name2" value="优快云"></property>
</bean>
</beans>
Id用于唯一标注该bean,class是指定要实例化哪个类,property用于设定bean的属性,其中name应该对应成员变量的setter函数,即如果setter函数是setName()那么name=”name”,如果是setName2()那么name=”name2”,注意不是和成员变量名称一致而是与setter函数名称一致,value显然是用于赋值。
4.写一个Main类用于执行main方法
package beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.hello();
}
}
5.运行后可以在控制台看到hello:优快云,至此这就是一个简单的Spring的HelloWorld程序。