搭建好开发环境后开始进行开发环境的测试。开发环境搭建请参考上一篇博客http://blog.csdn.net/qq_19259415/article/details/78752773
进入Spring Tool Suite的解压目录,进入sts-3.9.1.RELEASE目录,找到STS.exe文件,双击运行(可以建立桌面快捷方式)。首先会选择工作目录,随便找一个文件夹即可。
1、新建maven工程
点击file->new->Maven Project。如果没有Maven Project可以在other中查找。
选择新建一个简单项目
设置包名和项目名,这里工程类型选择jar文件就可。
点击finish,则创建好了一个maven项目。
这里maven项目中自动添加了jdk1.8,是因为我们在maven的settings.xml中设置了jdk版本。设置方法在我上一篇博客中。
2、修改pom.xml文件
在pom.xml文件中添加对spring的依赖,添加dependencies标签。pom.xml修改后如下所示。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bestcoder</groupId>
<artifactId>helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
</dependencies>
</project>
3、更新项目
右键单机项目->Maven->Update Project。点击确定,后Spring Tool Suite的右下角会出现进度条,这是Maven会从网上下载需要的jar包到本地Maven仓库。要保持网络畅通,否则可能下载失败。第一次可能需要一段时间进行下载,以后项目就可以直接从本地Maven仓库获取jar包。
更新成功后项目结构如下
项目中多了一下spring的jar包。
4 编写代码测试
4.1编写一个功能类的Bean
package com.bestcoder.helloworld;
import org.springframework.stereotype.Service;
@Service
public class FunctionService {
public String sayHello(String word) {
return "Hello "+word+" !";
}
}
这里使用@Service注解声明当前FunctionService类是Spring管理的一个Bean。其中,使用@Component、@Service、@Repository和@Controller是等效的,可根据需要选用。
4.2 使用FunctionService
package com.bestcoder.helloworld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UseFunctionService {
@Autowired
FunctionService functionService;
public String SayHello(String word) {
return functionService.sayHello(word);
}
}
使用@Autowired将FunctionService的实体Bean注入到UserFunctionService中的functionService变量中,functionService可以直接使用,不要new对象。
4.3 定义配置类
package com.bestcoder.helloworld;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.bestcoder.helloworld")
public class MyConfig {
}
使用@Configuration声明当前类是一个配置类。使用@ComponentScan,自动扫描包下所有使用@Service、@Component、@Repository、@Controller的类,并注解为Bean。
4.4 运行
编写main函数
package com.bestcoder.helloworld;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);
System.out.println(useFunctionService.SayHello("World"));
context.close();
}
}
使用AnnotationConfigApplicationContext 作为Spring 的容器,接受输入 一个配置类作为参数。
运行,控制台输出Spring加载的一些信息和Hello World !。