SpringBoot入门一

来源:互联网 发布:新闻 数据集 编辑:程序博客网 时间:2024/05/31 18:30

SpringBoot入门一

推荐:

  • Spring Boot系列文章
  • Spring Boot基础教程
  • Spring Boot参考指南
  • springboottutorial

项目属性配置

参考:

  • Spring Boot属性配置文件详解

可以使用properties文件,YAML文件配置。YAML文件相对来说更简洁一点。

如下的application.yml

server:  port: 8082  context-path: /girl

1.@Value("${属性名}")注解来加载对应的配置属性

如下的application.yml

server:  port: 8082  context-path: /girlcupSize: Bage: 20content: "cupSize: ${cupSize}, age: ${age}"

加载对应的配置

    @Value("${cupSize}")    private String cupSize;    @Value("${age}")    private Integer age;    @Value("${content}")    private String content;

2.@ConfigurationProperties会绑定properties中的值,并且支持层级关系

如下的application.yml

server:  port: 8082  context-path: /girlgirl:  cupSize: B  age: 20  content: "cupSize: ${girl.cupSize}, age: ${girl.age}"

创建一个类GirlProperties

@Component@ConfigurationProperties(prefix = "girl")public class GirlProperties {    private String cupSize;    private Integer age;    private String content;    public String getCupSize() {        return cupSize;    }    public void setCupSize(String cupSize) {        this.cupSize = cupSize;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public String getContent() {        return content;    }    public void setContent(String content) {        this.content = content;    }}

使用@ConfigurationProperties(prefix = "girl"),可以把girl对应的前缀下面的属性都映射过来,就不用使用@Value("${cupSize}")这种形式的注解。相当于把配置写到一个类中

测试如下:

@RestControllerpublic class HelloController {    @Autowired    private GirlProperties girlProperties;    @RequestMapping(value = "/hello", method = RequestMethod.GET)    public String say(){        return girlProperties.getContent();    }}

访问http://localhost:8082/girl/hello,浏览器显示cupSize: B, age: 20

3.开发环境和生成环境

我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事

对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot也不例外,或者说更加简单。

在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-test.properties:测试环境
  • application-prod.properties:生产环境

至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

如:spring.profiles.active=test就会加载application-test.properties配置文件内容

下面,以不同环境配置不同的服务端口为例,进行样例实验。

针对各环境新建不同的配置文件application-dev.propertiesapplication-test.propertiesapplication-prod.properties

在这三个文件均都设置不同的server.port属性,如:dev环境设置为1111,test环境设置为2222,prod环境设置为3333

application.properties中设置spring.profiles.active=dev,就是说默认以dev环境设置

测试不同配置的加载

  • 执行java -jar xxx.jar,可以观察到服务端口被设置为1111,也就是默认的开发环境(dev)
  • 执行java -jar xxx.jar --spring.profiles.active=test,可以观察到服务端口被设置为2222,也就是测试环境的配置(test)
  • 执行java -jar xxx.jar --spring.profiles.active=prod,可以观察到服务端口被设置为3333,也就是生产环境的配置(prod)

按照上面的实验,可以如下总结多环境的配置思路:

  • application.properties中配置通用内容,并设置
  • spring.profiles.active=dev,以开发环境为默认配置
  • application-{profile}.properties中配置各个环境不同的内容
  • 通过命令行方式去激活不同环境的配置

如下的形式,创建如下的三个application.yml

a.application.yml,指定为dev环境

spring:  profiles:    active: dev

b.application-dev.yml,开发配置

server:  port: 8083  context-path: /girlgirl:  cupSize: B  age: 20  content: "cupSize: ${girl.cupSize}, age: ${girl.age}"

c.application-prod.yml,生成配置

server:  port: 8084  context-path: /girlgirl:  cupSize:  age: 30  content: "cupSize: ${girl.cupSize}, age: ${girl.age}"

控制器

Controller使用

  • @Controller - 处理http请求
  • @RestController - Spring4之后新加的注解,原来返回json,需要@ResponseBody配合@Controller
  • @RequestMapping - 配置url映射
  • @PathVariable - 获取url中的数据
  • @RequestParam - 获取请求参数的值
  • @GetMapping - 组合注解,简化书写

参考3.2、组合的@RequestMapping变种

Spring 4.3 中引进了下面的注解 @RequestMapping 在方法层级的变种,来帮助简化常用 HTTP 方法的映射,并更好地表达被注解的方法的语义。比如,@GetMapping可以读作 GET @RequestMapping

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

数据库操作

JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一个规范的产品有Hibernate、TopLink等

Spring Data JPA是Spring基于Hibernate开发的一个JPA框架。

参考:

  • spring data jpa介绍

要使用库,在pom.xml中添加2个依赖组件:

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>

例子说明

1.一些设置

application.yml中设置,如下:

spring:  profiles:    active: dev  datasource:    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://127.0.0.1:3306/dbgirl    username: root    password:  jpa:    hibernate:      ddl-auto: create    show-sql: true
  • ddl-auto: create表示程序运行,每次都会创建新的表,如果原来存在表,则会先把它删除,通常使用的是update,会保留原来的数据

2.创建实体类

创建实体类Girl,有如下的注解:

@Entitypublic class Girl {    @Id    @GeneratedValue    private Integer id;    private String cupSize;    private Integer age;    public Girl(){    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getCupSize() {        return cupSize;    }    public void setCupSize(String cupSize) {        this.cupSize = cupSize;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}

注解说明,可参考JPA之Entity注解说明

  • @Entity标明该类为一个实体类
  • @Id标明该属性对应数据表中的主键
  • @GeneratedValue 通过 strategy 属性指明主键生成策略,默认情况下, JPA 自动选择一个最适合底层数据库的主键生成策略

运行程序,数据库会自动创建一个名为girl的表,如下:

CREATE TABLE `girl` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `age` int(11) DEFAULT NULL,  `cup_size` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8

3.数据库操作

Spring-Data-JPA操作数据库非常简单,不需要写一句sql语句

a.首先创建一个GirlReponsitory,继承自JpaRepository,如下,Integer表示主键类型

public interface GirlReponsitory extends JpaRepository<Girl,Integer>{}

b.在控制器中,使用方式如下:

    @Autowired    private GirlReponsitory girlReponsitory;    /**     * 查询列表     * @return     */    @GetMapping(value = "/girls")    public List<Girl> girlList(){        return girlReponsitory.findAll();    }

可能会出现的问题:

  • springboot +jpa 读写分离 遇到JavassistLazyInitializer及解决

事务管理

在Spring Boot中,当我们使用了spring-boot-starter-jdbc或spring-boot-starter-data-jpa依赖的时候,框架会自动默认分别注入DataSourceTransactionManager或JpaTransactionManager。所以我们不需要任何额外配置就可以用@Transactional注解进行事务的使用。

参考:

  • Spring Boot中的事务管理

其它

教程:

  • 2小时学会Spring Boot
原创粉丝点击