spring boot学习笔记(一)
一,初识spring boot
spring boot 有4个核心模块,实现很多独特功能。
1.1 自动配置
针对spring应用程序,实现自动提供相关配置,简化spring大量繁多的配置文件。
在原有的spring工程中,常见很多配置项。而这些配置项。spring boot中只要在其classpath发现相应的对象,它就会自动注入到spring容器中。
1.2 起步依赖
起步依赖就是特殊的共用库管理工具,它提供了像maven等库管理工具类似的功能。但是,通过分类之后更加简洁。
1.3 命令行界面
spring boot CLI 利用起步依赖和自动配置让每个人专注与代码本身,抛开了依赖以及环境等因素。
1.4 Actuator
Actuator提供在运行时检视应用程序内部情况的能力。
包括:
spring 容器中bean ,
spring boot自动配置决策,
应用程序环境变量等配置,
应用程序中线程的当前状态,
应用程序最近处理过的HTTP请求的追踪情况,
内存用量,立即回收,web请求以及数据源用量相关指标
并通过web站点以及shell界面提供信息。
二, hello world!
开发第一个spring boot 应用。
2.1 使用起步依赖
起步依赖自动帮spring boot配置好了所有的依赖关系,使开发者不必须关心每一个依赖的开源组件以及他们对应的版本。而我们需要做的是告诉spring boot 我们的应用程序中将要使用的组件(web)。
2.2 覆盖起步依赖引入的传递依赖
当然如果你需要去掉spring boot依赖包中某些传递依赖,比如项目瘦身.覆盖依赖等等 ,spring boot 也提供了足够的自由度,排除传递依赖。
在Maven里,可以用<exclusions>元素来排除传递依赖。
栗子:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
如果只是覆盖某个版本,可以直接在pom中引入对应版本的组件。
栗子:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
覆盖版本时,一定要谨慎。现有版本依赖关系配置spring boot都做过详细的测试,若替换某些组件的版本,可能引发依赖问题。所以替换组件时,一定要谨慎若非必须无需替换。
2.3 创建第一个spring boot应用
spring boot 官网(https://start.spring.io )提供spring initializr的方式自动生成工程,具体操作不详细赘述。
直接上栗子:
DemoApplication.java
@SpringBootApplication
@RestController
public class DemoApplication {
@RequestMapping("/")
public String home(){
return "hello world!";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
使用寥寥几行代码后端接口就完成了。
下面时pom依赖,pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
spring boot 配置项寥寥无几,对比之前的spring项目,简单几行代码便可以实行以恶web应用并直接运行,spring boot 内嵌了jtty和tomcat ,使可以直接java -jar demo.jar 运行。
三 , 数据库应用
使用数据库是开发基本应用的基础,目前已有开发框架,我们已经不用关心数据库访问代码以及底层代码,我们在更高层使用数据库。而spring boot突破原有框架,在框架的更高层次访问数据库。
3.1 mysql使用
spring boot 使用JPA 库实现对数据库的操作。 JPA:POJO持久化标准规范,作为java数据库模型中的ORM层,映射对象层,通过映射关系持久化java 普通对象到数据库中。
3.1.1 maven依赖
mysql以及JPA的maven依赖 pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3.1.2 创建实体模型
User.java :
package com.example.demo.entity;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name="user")
public class User {
@Id
@Column(name="id",nullable = false)
@GenericGenerator(name="idGenerator", strategy="uuid") //这个是hibernate的注解/生成32位UUID
@GeneratedValue(generator="idGenerator")
private String id;
@Column
private String name ;
@Column
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.1.3 创建 jpa dao访问层
UserRepository.java :
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,String> {
}
3.1.4 创建数据库配置
application.yml :
server:
port: 8000
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: root
jpa:
hibernate:
ddl-auto: create
show-sql: true
3.1.5 启动应用
package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@ComponentScan("com.example.demo.**.entity")
@SpringBootApplication
@RestController
@RequestMapping("/")
public class DemoApplication {
@Autowired
UserRepository userRepository;
@RequestMapping("/test")
public String index(){
User u = new User();
u.setName("xxx");
userRepository.save(u);
return "test jpa";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
直接运行,建议先使用maven编译之后再运行。entity对应的表不能正常创建的情况。
3.2 使用redis
关系型数据库在性能上总是有这样那样的缺陷,所以在使用传统关系型数据库时,会与高效存取功能的缓存系统结合使用,用来提高系统的性能。redis 是缓存系统中的佼佼者,是一个高性能的key-value数据库。
3.2.1 redis spring boot 依赖
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>redis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2.2 redisTemplate 类
简单封装 redisTemplate 类的setting和Getting接口
package com.example.redis.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
@Service
public class RedisSevice {
@Autowired
private RedisTemplate redisTemplate;
public void set(final String key,Object value) {
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public void set(final String key,Object value,Long timeout) {
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value,timeout, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
}
public Object get(final String key){
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
}
3.2.3 redis配置
application.properties:
spring.redis.database=0
spring.redis.host=192.168.99.100
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.jedis.pool.max-idle=8
# 连接超时时间(毫秒)
spring.redis.timeout=1000ms
3.2.4 redis安装
1)redis window下部署
redis 64位下载地址:https://github.com/ServiceStack/redis-windows
启动redis
命令行下:
redis-server.exe redis.windows.conf
使用reids-cli
命令行下:
redis-cli.exe
1)redis window下docker容器部署
这里,在windows环境下,使用docker部署redis
docker安装使用docker-tools
启动docker:
Starting "default"...
(default) Check network to re-create if needed...
(default) Windows might ask for the permission to configure a dhcp server. Sometimes, such confirmation window is minimized in the taskbar.
(default) Waiting for an IP...
Machine "default" was started.
Waiting for SSH to be available...
Detecting the provisioner...
Started machines may have new IP addresses. You may need to re-run the `docker-machine env` command.
Regenerate TLS machine certs? Warning: this is irreversible. (y/n): Regenerating TLS certificates
Waiting for SSH to be available...
Detecting the provisioner...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
## .
## ## ## ==
## ## ## ## ## ===
/"""""""""""""""""\___/ ===
~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ / ===- ~~~
\______ o __/
\ \ __/
\____\_______/
docker is configured to use the default machine with IP **192.168.99.100**
For help getting started, check out the docs at https://docs.docker.com
下载redis 镜像
docker命令:
docker pull redis
启动redis:
docker run --name redis -p 6379:6379 -v /d/redis/data:/data redis
使用redis连接工具连接虚拟IP(192.168.99.100)的6379端口,连接正常。
3.3 使用MongoDB
对MongoDB不太熟悉。学习之后再来更新
3.4 使用Neo4j
对Neo4j不太熟悉。学习之后再来更新
Edit By MaHua