创建一个项目

1). 选择Spring Initializr 2). 如图 3). 选择依赖

启动项目报错:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

原因是mybatis没有配置,去掉pom文件中引入的mybatis发现可以正常启动。

测试请求:

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }
}

访问http://localhost:8080/hello可以看到请求结果。

使用springmvc返回string或者json的话就直接用@RestController。如果想要页面跳转的话,就使用@Controller。

引入mybatis

测试:

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://127.0.0.1:5432/linyi_sde?currentSchema=business
    username: tyrad
    password:

jar包

m

springboot自动帮我们集成Tomcat,我们无需另外部署到tomcat。

启动: java -jar 文件名

application.yml 开发环境生产环境配置

server:
  port: 8081
  servlet:
    context-path: /api/v1
    session:
      cookie:
        name: BIUSID
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://127.0.0.1:5432/xxx
    username: tyrad
    password:
  profiles:
    active: dev

#可以使用分割,也可以使用不同的文件

# 默认的profile为dev,其他环境通过指定启动参数使用不同的profile,比如:
#   测试环境:java -jar my-spring-boot.jar --spring.profiles.active=test
#   生产环境:java -jar my-spring-boot.jar --spring.profiles.active=prod

---
# 开发环境配置
spring:
  profiles: dev
server:
  port: 8081

---
# 测试环境配置
spring:
  profiles: test
server:
  port: 8082

---
# 生产环境配置
spring:
  profiles: prod
server:
  port: 8083

加载更多配置

spring:
  profiles:
    include: db,mq

使用@ConfigurationProperties读取配置文件

新建文件user.yml

profile:
  age: 90
  sex: 1
  name: xiaoming

读取举例

//模型
package cc.tyrad.smartservice;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

@Data
@ConfigurationProperties(prefix = "user")
@Service
public class User {
    private String sex;
    private String name;
    private String age;
}

//Controller
@RestController
public class HelloController {
    @Autowired User user;
    @RequestMapping("/hello")
    public String hello() {
        return "hello world:" + user.getName();
    }
}

参考

http://spring.io/projects/spring-boot

Spring Boot 入门学习

https://www.kancloud.cn/cxr17618/springboot/435772