一、 目标
- 使用SpringBoot编写控制器
- 扩展常用的DAO层、Service层
二、 工程结构
注意:controller、service、dao这些包都放在Starter类所在的子包下面!
三、 代码
- 增加org.springframework.boot依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
- 编写boot启动调用的主方法类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Starter {
public static void main(String[] args) {
SpringApplication.run(Starter.class, args);
}
}
- 编写SampleController控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import cn.dectfix.myproject.service.TestService;
@Controller
@RequestMapping("/s1")
public class SampleController {
@Autowired
private TestService testService;
@RequestMapping("/h1")
@ResponseBody
String home1() {
testService.test();
return "Hello World1!";
}
@RequestMapping("/h2")
@ResponseBody
String home2() {
testService.test();
return "Hello World2!";
}
}
- 编写服务层
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.dectfix.myproject.dao.TestDAO;
@Service
public class TestService {
@Autowired
private TestDAO testDAO;
public void test(){
testDAO.test();
System.out.println("TestService!");
}
}
- 编写DAO层
import org.springframework.stereotype.Repository;
@Repository
public class TestDAO {
public void test(){
System.out.println("TestDAO!");
}
}
四、 启动项目
以application方式启动SpringBoot程序,默认情况下访问8080端口,如我这里访问http://localhost:8080/s1/h1即可看到控制器打印出的信息。