SpringBoot的基本使用
环境: jdk1.8 maven eclipse
- SpringBoot 入门
- 创建一个maven 工程 jar工程
- 父工程的依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
-
- 如果要使用springmvc 就要依赖springboot提供的web jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-
- 创建springboot的maven插件(Spring Boot Maven plugin)
创建springboot的maven插件的目的:能够以maven的方式为应用提供springboot的支持,即为springboot的应用提供了执行maven的操作的可能.Spring Boot Maven plugin能够将Spring Boot应用打包为可执行的jar或war文件,然后以通常的方式运行Spring Boot应用。
<build>
<finalName>打包时的包名称</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>主配置的类(打包时使用)</mainClass>
</configuration>
</plugin>
</plugins>
</build>
-
- 编写springboot的配置类
示例代码如下:
@SpringBootApplication // 开启自动配置 和标记此类为配置类 扫描的包是 当前包即一下的多有包
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args); // 运行
}
}
在配置类的包中编写一个实体类和控制层类 如:
实体类:
public class Person implements Serializable {
private int id;
private String name;
@JSONField(format="yyyy-MM-dd HH")
private Date brithDate;
.........
控制层类:
@Controller
public class Demo01 {
@RequestMapping("/ok")
@ResponseBody
public Person test01() {
Person p = new Person();
p.setId(12);
p.setBrithDate(new Date());
p.setName("张三");
return p;
}
}
Springboot基本搭建完成 ,启动项目 ,项目启动后 Tomcat的默认端口号是8080 这可以使用 http://localhost:8080/ok 访问
响应的结果是:
{ "brithDate":"2019-02-13 11", "id":12, "name":"张三" }
问题: 为什么 这样配置就可以实现springmvc的基本操作呢??
原因在于我们引用的web jar 在使用@SpringBootApplication 时 springboot自动配置了dispatcherServlet 等的配置.
自动配置的包在:spring-boot-autoconfigure-2.1.1.RELEASE.jar 中
- Springboot 全局配置文件
- 全局配置文件的名称:application.yml 或者是 application.properties.
- 全局配置文件的存放位置:放在classpath下
-
- 部分全局配置文件的内容:
spring.profiles.active=dev profiles的配置
logging.config=classpath:logback-config.xml 日志文件路径
spring.resources.static-locations=classpath:/static/ 访问静态资源的路径
spring.http.encoding.force=true http请求时的编码使用utf-8
server.port=8089 配置访问的端口号
server.servlet.context-path=/ww 配置访问的路劲
这样从新启动项目 端口号就改为了8089 访问的路径为: http://localhost:8080/ww/ok
- Profile的配置
- 在classpath下 以application-*.properties的方式命名
如:
-
- 在全局配置文件中的使用方式
pring.profiles.active=dev profiles的配置
这样读取的使用application-dev.properties中配置的内容. 如果是:pring.profiles.active=prop 则读取的是application-prop.properties中的内容
- 获取自定义配置文件中的值
- 使用@Value的方式获取
首先在classpath中编写一个db.properties 配置文件 文件中的内容为:
jdbcc.url=jdbc:mysql://localhost:3306/db
jdbcc.password=123456
其次:在配置类中加入@PropertySource(value="classpath:db.properties")
@PropertySource(value="classpath:db.properties")
public class ApplicationConfig {}
最后:在需要取值的类中使用@value(“${key}”) 取值
如:
@Value("${jdbcc.url}")
private String url;
@RequestMapping("/ok")
@ResponseBody
public String test01() {
return url;
}
-
- 使用类行安全的方式取值
首先在classpath中编写一个db.properties 配置文件 文件中的内容为:
jdbcc.url=jdbc:mysql://localhost:3306/db
jdbcc.password=123456
@PropertySource(value="classpath:db.properties")
public class ApplicationConfig {}
最后:
@ConfigurationProperties(prefix="jdbcc") // 使用类型安全的配置
public class Demo02 {
private String url;
private String password;
@RequestMapping("/image")
@ResponseBody
public String test01() {
return url+",密码:"+password;
}
................
}
注意:使用类型安全的方式取值是属性必须要有get和set方法
- springboot的日志管理
Springboot默认使用的是logback 日志管理,在classpath中创建日志管理配置文件,命名为:
logback.xml 或者是logback-spring.xml 这是springboot的默认命名 启动项目时直接就可以加载,如果名称为其他的话必须在application.xml中配置一下内容:
logging.config=classpath:logback-config.xml
如果想使用log4j作为日志管理则需要一下步骤:
- 修改pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
红色字体是排除:springboot自带的日志管理 即logback
- 在resources中创建log4j.properties
- Springboot静态文件的存放位置
- springboot静态文件默认存放在classpath下的static目录 或者是 public目录中.
-
- 如果静态文件存放的目录不在static 或者 public 时 要在application.properties中配置
spring.resources.static-locations=classpath:/static/
- Springboot 配置开发模式
在pom.xml中加入:
<!-- 加入以下两个依赖,代码做了修改,不用重新运行 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency
- Springboot自定义消息转化器
Springboot自身是使用Jackson做为json的格式化 ,如果想用fastJson这必须自定义消息转化器.
以fastjson为例,自定义消息转化器
-
- jar包的依赖
<!-- 使用fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
-
- 在配置类配置消息转化器
@Bean
public HttpMessageConverters converters() {
// 创建fastjson消息传化器
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
// 创建fastjson配置类
FastJsonConfig config = new FastJsonConfig();
// 对json进行格式化
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
converter.setFastJsonConfig(config);
HttpMessageConverter<?> conn = converter;
return new HttpMessageConverters(conn);
}
这样就可以使用fastjson了
- 使用ObjectMapper对日期格式化
配置方法:
@Bean
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());
return objectMapper;
}
这样使用ObjectMapper转json时 时间就格式化为:yyyy-MM-dd HH:mm:ss
- Springboot中全局异常的处理
- 编写一个全局异常的配置类 在配置类上使用@@ControllerAdvice注解
- 编写方法在方法上使用 @ExceptionHandler(value=异常的类)
如:
@ControllerAdvice
public class ExceptionAll {
@ExceptionHandler(value=Exception.class)
@ResponseBody
public String HanderAllExcption() {
return "全局异常的拦截";
}
}
- springboot整合jsp
Springboot整合jsp时 项目必须使用war包
11.1 jar的依赖
<!-- 整合jsp -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
11.2 application.properties中配置视图解析器
spring.mvc.view.prefix= /jsp/
spring.mvc.view.suffix= .jsp
整合完成
- Springboot中使用quartz
- 在Java配置类中开启定时任务 @EnableScheduling
- 创建任务类 在方法中使用
@Scheduled(fixedRate=1000)
public void run() {
System.out.println("任务开始");
}
- Springboot与mybatis整合
基于xml的配置
-
- jar包的依赖
<!-- 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
-
- application.yml中配置数据库连接信息
spring:
datasource: // 配置数据源
url: jdbc:mysql://dec.dev106.haichuang.pro:3306/sql_dec_dev106
username: sql_dec_dev106
password: r3axJf2bQd6rzanR
type: com.alibaba.druid.pool.DruidDataSource // 连接池对象
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mybatis:
mapper-locations: classpath:mapping/*.xml // mapper.xml 存放的位置
pagehelper: // 分页助手的配置
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
-
- 开启mapper扫描
@SpringBootApplication
@MapperScan(value= {"zy.springbootweb.mapper"}) // mapper 需要单独扫描
public class ApplicationConfig extends SpringBootServletInitializer{
这样就整合完成了
文件目录结构:
基于注解的配置:
public interface SysUserDoMapper {
@Select("select user_id as userId, user_name as userName, user_role_name as userRoleName, user_password as userPassword, user_permission as userPermission,"
+ " user_state as userState, create_time as createTime from sys_user\r\n" +
" where user_id = #{userId}")
SysUserEntity selectAnnotation(@Param("userId")Integer userId);
}
- springboot的事务管理
Springboot的事务管理:只需要在存在事务的方法上加入@Transaction就可以了