SpringBoot的demo

作为开发人员,那么原始的整合spring+springMVC+myBatis是比较痛苦的,xml文件配置过多。很多bean需要配置,经常出错

那么现在通过springBoot这个框架基本可以做到无配置文件来启动我们的springMVC+spring+myBatis框架的系统

(博主在这边文章中没有导入mybatis的使用,使用springBoot+spirngMVC+spring的使用)

首先创建Maven项目

1.在pom文件中导入 springBoot的 parent

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
 </parent>

2.导入web依赖

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3.接下来 我们就可以来编写 java 代码  dao-->service--->controller (模拟数据操作)

3.1 先搭建好 package结构

  

3.2 在dao中 写一个 dao类    @Repository (标记为一个持久层组件)

@Repository
public class HelloDao {

    public void helloDao(){
        System.out.print("hello Dao");
    }
}

3.3 在service 中写一个 service类  @Service(标记为一个业务层组件) 并且注入HelloDao 类 

@Service
public class HelloService {
    @Resource
    private HelloDao helloDao;
    public void hello(){
        helloDao.helloDao();
        System.out.print("hello service");
    }
}

3.4 在controller中 编写 controller类   并注入HelloService

@Controller
//@RestController
public class HelloController {
    @Resource
    private  HelloService helloService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        System.out.print("hello world");
        helloService.hello();
        return "index";
    }
}

注意:@RestController用法 可以替代 @Controller与@ResponseBody

3.5 在基础包com.sxt下编写启动类  主需要一个main方法即可

@SpringBootApplication
public class TestdenoApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestdenoApplication.class, args);
    }
}

我们直接 使用 java-->run 启动  

启动成功。接下来我们通过浏览器来访问  项目地址 localhost:8080/hello

通过访问浏览器,我们可以在Idea 工具的控制台看到 有打印语句。springBoot一个简单demo就完成了。是不是很简单。

做到了无配置文件使用。很方便

猜你喜欢

转载自blog.csdn.net/xiezhi_1130/article/details/84852126
今日推荐