本文主要是介绍实战代码(十二):Springboot 常用代码速查笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、关闭banner
在配置文件application.yml
中添加
spring:main:banner-mode: 'off'
二、将tomcat替换为undertow
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></exclusion></exclusions>
</dependency>
<!-- 将tomcat替换为undertow -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
三、开启热部署
<!-- 热部署 optional为true才会生效 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional>
</dependency>
四、Springboot内置的定时任务
// 允许启用定时任务
@EnableScheduling// 每隔一分钟执行一次
@Scheduled(fixedRate = 60 * 1000)// 每天0点1分执行一次
@Scheduled(cron="0 1 0 * * *")
五、读取配置文件中的配置项
@Value("${rmq.namesrvAddr}")
private String namesrvAddr;
六、读取自定义的配置文件
依赖引入
<!-- 自定义的元数据依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional>
</dependency>
配置文件
rmq.namesrvAddr=192.168.1.10:9876
rmq.consumeThreadMin=10
rmq.consumeThreadMax=20
rmq.consumerGroup=epark
rmq.clientLogDir=logs/rocketmq_client
读取配置文件
@Component
@ConfigurationProperties(prefix = "rmq")
@PropertySource(value = "rocketmq-config.properties")
@Data
public class RocketMQProperties {private String namesrvAddr;private int consumeThreadMin;private int consumeThreadMax;private String consumerGroup;private String clientLogDir;
}
七、给接口配置统一的前缀
server:servlet:context-path: /demo
八、初始化
commandLine是项目启动后需要执行的操作,优先级通过Value实现,数值越小优先级越高
@Order(value=2)
@Component
public class ApplicationInit implements CommandLineRunner { }
九、指定日志配置文件
logging.config=classpath:logback-spring-dev.xml
十、解决跨域问题
@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();final CorsConfiguration corsConfiguration = new CorsConfiguration();/*是否允许请求带有验证信息*/corsConfiguration.setAllowCredentials(true);/*允许访问的客户端域名*/corsConfiguration.addAllowedOrigin("*");/*允许服务端访问的客户端请求头*/corsConfiguration.addAllowedHeader("*");/*允许访问的方法名,GET POST等*/corsConfiguration.addAllowedMethod("*");urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);return new CorsFilter(urlBasedCorsConfigurationSource);}
}
这篇关于实战代码(十二):Springboot 常用代码速查笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!