Swagger整合
- 在项目中自动去生成接口文档,只需要在控制器以及控制器方法,实体类中添加一些注解,即可生成一个完整的接口文档
- 添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
- 编写配置类
- @EnableSwagger2 扫描指定Swagger注解,并生成接口文档
@Configuration
//允许在指定的类中使用Swagger提供的注解
//容器会自动扫描指定Swagger注解,并生成接口文档
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 指定要生成接口文档的Controller所在的包
.apis(RequestHandlerSelectors.basePackage("com.sy.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//接口文档的标题
.title("用户管理系统RESTful接口文档")
//接口文档的简介
.description("这个是接口文档的简介")
// 服务条款网址
.termsOfServiceUrl("http://blog.csdn.net/forezp")
//接口的版本号
.version("v1.0")
// 许可证
.license("苏LP12345")
//联系方式:公司名称、官网地址、联系用的邮箱
.contact(new Contact("上元教育", "http://www.sy.com", "xxx@sy.com"))
.build();
}
}
- 编写控制器,在控制器中添加注解来对接口方法以及控制器类进行说明
- @Api注解:相当于指定了当前控制器在接口文档中的一个概要
- @ApiOperation注解:对具体的方法的作用进行说明
- value–参数说明
- notes-其他信息说明
- @ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
- name–参数名(前端传递给后台的真正的参数名,不是方法的形式参数名)
- value–参数说明
- required–是否必填
- @ApiIgnore 使得当前的方法不被写入接口文档中
- @ApiModel 对存入参数的pojo类型的描述
- value-名称
- description-描述
- @ApiModelProperty 在pojio类中对属性字段进行说明
- value-名称
- name-属性名
- example-示例
@org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest/v1.0")
//@Api注解:相当于指定了当前控制器在接口文档中的一个概要
@Api(tags = "测试用的模块")
public class RestController {
// 不指定请求类型,则该接口会生成7种不同的请求方式
@RequestMapping(value = "user1", method = {RequestMethod.POST})
//@ApiOperation注解:对具体的方法的作用进行说明
@ApiOperation(value = "获取用户信息", notes = "根据用户姓名和年龄得到用户信息")
// @ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
// name–参数名(前端传递给后台的真正的参数名,不是方法的形式参数名)
// value–参数说明
// required–是否必填
public Map<String, Object> user1(
@ApiParam(value = "用户名", name = "userName", required = true) @RequestParam String userName,
@ApiParam(value = "年龄", name = "age", required = true) @RequestParam int age) {
Map<String, Object> map = new HashMap<>();
map.put("userName", userName);
map.put("age", 18);
return map;
}
Quartz整合 定时任务调度框架
- 通过给定一个时间表达式来使得Quartz能够在指定的时间内周期执行某个操作或等到某个时间再去执行某个操作
- 时间表达式:CRON表达式
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
- 添加配置类
@Configuration
public class QuartzConfig {
@Bean
public Scheduler scheduler() throws SchedulerException {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//newJob中的参数:任务类
JobDetail oneJob = JobBuilder.newJob(Task1.class).withIdentity("task1", "group1").build();
TriggerBuilder<Trigger> newTrigger = trigger();
newTrigger.withIdentity("trigger1", "group1");
//cronSchedule中的参数:cron表达式,用来指定任务的执行时间
newTrigger.withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?"));
Trigger oneTrigger = newTrigger.build();
scheduler.scheduleJob(oneJob, oneTrigger);
scheduler.start();
return scheduler;
}
@Bean
public TriggerBuilder<Trigger> trigger() {
return TriggerBuilder.newTrigger();
}
}
- 添加具体的任务执行类 实现Job接口
public class Task1 implements Job {
/**
* 该方法定义了任务需要执行的具体过程
*
* @param jobExecutionContext
* @throws JobExecutionException
*/
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("任务执行...");
}
}
整合事务
用注解方式的声明式事务
- 配置数据源事务管理器
/**
* 配置数据源事务管理器
*/
@Bean
public PlatformTransactionManager txManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
- 在数据源配置类中打上注解
- 相当于tx:annotation-driven,此时可以使用@Transactional进行事务管理
- @EnableTransactionManagement
- 需要管理的方法上打上注解,进行事物管理
- @Transactional
通过XML方式进行配置
- 添加依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
- 配置数据源事务管理器
- 配置通知管理
- 配置切点切面联系
@Configuration
public class TransactionalConfig {
// 事务方法超时时间设置
private static final int TX_METHOD_TIMEOUT = 5;
// AOP切面的切点表达式
private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.sy.service.*.*(..))";
// 注入事务管理器
@Autowired
private PlatformTransactionManager transactionManager;
@Bean
public TransactionInterceptor txAdvice() {
NameMatchTransactionAttributeSource txAttributeS = new NameMatchTransactionAttributeSource();
//DML事务
RuleBasedTransactionAttribute requiredAttr = new RuleBasedTransactionAttribute();
//事务的传播行为
requiredAttr.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//事务的隔离级别
//requiredAttr.setIsolationLevel();
//事务的超时时间
requiredAttr.setTimeout(TX_METHOD_TIMEOUT);
//遇到哪些异常需要进行回滚
requiredAttr.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
//DQL:只读的事务
RuleBasedTransactionAttribute supportsAttr = new RuleBasedTransactionAttribute();
supportsAttr.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
//是否是只读的
supportsAttr.setReadOnly(true);
Map<String, TransactionAttribute> txMethod = new HashMap<String, TransactionAttribute>();
//DML事务
txMethod.put("save*", requiredAttr);
txMethod.put("add*", requiredAttr);
txMethod.put("insert*", requiredAttr);
txMethod.put("update*", requiredAttr);
txMethod.put("transfer*", requiredAttr);
//DQL只读事务
txMethod.put("find*", supportsAttr);
txMethod.put("select*", supportsAttr);
txMethod.put("get*", supportsAttr);
txAttributeS.setNameMap(txMethod);
TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, txAttributeS);
return txAdvice;
}
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
//切点
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
//将切点和切面机进行关联
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
}
logback 日志文件
-
SpringBoot项目中在官方文档中说明,默认已经依赖了一些日志框架。而其中推荐使用的就是Logback
-
SpringBoot已经依赖了Logback所以不需要手动添加依赖
-
Spring Boot 只有1.3.x和1.3.x以下版本才支持log4j的日志配置,1.3.x以上版本只支持log4j2,logback的日志配置
-
LogBack读取配置文件的步骤
- 尝试classpath下查找文件logback-test.xml
- 如果文件不存在,尝试查找logback.xml
- 如果两个文件都不存在,LogBack用BasicConfiguration自动对自己进行最小化配置,这样既实现了上面我们不需要添加任何配置就可以输出到控制台日志信息
-
直接将xml文件放入resources
- 常见的自定义配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
<property name="LOG_HOME" value="/home" />
<!-- 控制台输出 -->
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
%msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名 -->
<FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log
</FileNamePattern>
<!--日志文件保留天数 -->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
%msg%n</pattern>
</encoder>
<!--日志文件最大的大小 -->
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
- 如果要打印mybatis输出的SQL语句
- logging.level.com.sy.mapper=debug
SpringBoot中的其它注解
@Profile
- 为了能够使得SpringBoot应用在不同的环境中进行灵活的切换
- 开发环境
- 测试环境
- 生产环境
- @Profile注解允许在SpringBoot应用中对相同的参数在不同的环境下分别进行配置
通过激活的方式来指定需要使用哪个环境下的配置信息 - (一)用法一
- 准备不同的applicaiton-环境名.properties
- 在不同的properties文件中指定相同参数的不同配置
- 最后在application.properties中通过spring.profiles.active指定要激活哪个环境下的配置信息
- 如果被激活的环境中指定了和application.properties中相同的配置项
- 则激活环境中的配置会覆盖application.properties中的配置
- 语法:spring.profiles.active=dev
- (二)用法二
- 直接在某一个特定的配置类上去添加Profile注解
- 对于SpringBoot应用中只有某些Bean需要指定特定的环境,则可以将@Profile注解直接加在配置类上
@PropertySource
读取指定properties配置文件,将其中的值注入到类中作为属性
- 编写一个properties配置文件
- 需要在类中通过@PropertySource注解读取配置文件(可以写在启动类上或其他类中)
- @PropertySource({“classpath:app.properties”})
- 通过@Value注解结合spEL注入
- @Value("${app.param1}")
@ImportResource
- 引入Spring配置文件,SpringBoot尽管是崇尚0配置文件,但是有些框架的配置不得不通过XML配置获取使用XML配置更加简单,所以有时还是会引入XML文件的
条件注解
- 有一些对象的实例化操作是在引入了某些依赖或添加了某些配置信息以后自动来完成的(对象的创建需要满足一定的条件),此时可以使用SpringBoot中提供的条件注解来完成这个过程
- 定义条件类,实现Condition接口
public class User1Condition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//方法的返回值决定了当前的条件是否成立
//可以从容器中获取Bean对象
//conditionContext.getBeanFactory().getBean()
//获取环境的配置参数
//conditionContext.getEnvironment().getProperty(key);
return true;
}
}
- 在@Bean暴露Bean对象的地方,指定当前Bean的实例化条件
- @Conditional(User1Condition.class)