1、下载Spring所依赖的jar包:
选择合适的版本,比如我选当前最新的5.06。点击进入后下载,下载spring-framework-5.0.6.RELEASE-dist.zip 的文件。
解压到合适的目录,解压后的文件格式如下,等下要用到lib目录下的jar包:
2、打开Eclipse并创建Java项目,项目名合适就行,我命名为FirstSpringPro,点击Finish:
3、右击项目名新建Folder(目录),取名为lib,然后将步骤1的解压缩包下的libs目录下的4个Spring jar包拷贝到这个目录中。另外还有两个日志包log4j-1.2.17.jar和commons-logging-1.2.jar,它们的下载地址可见我的另一篇“Mybatis初体验“博客,在下载好的MyBatis解压包的lib目录下:
完成后lib目录结构如下:
4、分别右击这些jar包,并在弹出的快捷菜单中选择Build Path——> Add to Build Path命令,将这些jar包添加到项目的构建路径中,完成后如下:
5、开始编码。
①在src目录下创建com.shw包,并在包中新建一个名为HelloWorld的类,编码如下:
package com.shw;
public class HelloWorld {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
public void show() {
System.out.println("Welcome " + userName + " to study Spring!");
}
}
②在项目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">
<!-- Configuring a bean -->
<bean id="helloWorld" class="com.shw.HelloWorld">
<!-- Assessments for Properties -->
<property name="userName" value="Richard"></property>
</bean>
</beans>
③在com.shw包编写测试类TestHelloWorld,它会加载applicationContext.xml配置文件,获取HelloWorld实例,并调用类中的show()方法在控制台输出信息,编码如下:
package com.shw;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestHelloWorld {
public static void main(String[] args) {
// Loading applicationContext.xml
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// Getting instance of configuration
HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");
// Invoke method
helloWorld.show();
}
}
④编辑日志属性文件,配合前面的日志jar包使用,没有这一步也能运行,但是有警告。在src目录下新建log4j.properties文件,编码如下:
# Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern= %d %p [%c] - %m%n
最后看一下项目的总体结构:
6、运行结果:
小结:
Spring可以降低类之间的耦合。我们看到在测试类中并没有new一个HelloWorld对象,而是通过Spring的配置文件把类加载进来,这就在一定程度上降低了类之间的耦合关系!