从本节开始深入介绍springboot的特性,首先从启动入手,springboot的启动类就是main方法的类,一般位于工程根目录下,使用@SpringBootApplication修饰,main方法里边直接使用静态方法run来启动该进程。
package com.crazyice.lee.accumulation.file;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配合的配置文件application.yml里边必须设定服务端口。服务正常启动的日志输出如下:

启动异常
最常见的异常是端口被占用,这时通过netstat、lsof等命令可以查看端口使用情况,重新配置一个未使用的端口再次启动即可。如果要查看更详细的运行日志,可以在启动进程的时候添加--debug参数。
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
懒加载
springboot允许懒加载模式进行bean的初始化,也就是bean初始化只在需要使用的时候,这样可以加快启动速度,降低系统资源占有。但是懒加载也会导致运行时异常不能及时发现、内存分配不足等问题,所以缺省情况下不开放懒加载策略,建议在开发、测试阶段禁止懒加载,生产环境开放懒加载策略。
在application.yml文件里边通过配置开启懒加载策略:
spring:
main:
lazy-initialization: true
也可以针对每个bean设置懒加载策略,使用@Lazy注解,@Lazy(true)开启、@Lazy(false)关闭。
定制个性化banner
banner是springboot进程启动的时候一文本的方式显示的信息,缺省情况下如下:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.0.RELEASE)
可以通过配置关闭此功能,也可以自定义一些有意思的banner信息。
- 关闭banner
在application.yml里边配置spring.main.banner-mode:"off"即可关闭。 - 自定义banner
以文本格式编写banner.txt文件,里边可以以变量的方式引入一些参数,也可以直接提供图片作为banner内容,支持gif/png/jpg格式。对这些小情趣感兴趣的可以百度一下,有很多资源。
运行参数获取
springboot程序运行的时候可以通过命令行的方式传递一下参数及配置进去,使得程序更加的灵活。
package com.lance.mail.springbootmail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import java.util.List;
@Slf4j
@SpringBootApplication
public class SpringBootMailApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMailApplication.class, args);
}
@Component
public class MyBean{
@Autowired
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
log.info("{}-{}",debug,files);
}
}
}
命令行为
$java -jar SpringBoot-Mail-dev.jar --debug key1 key2 key3
执行结果
2019-08-01 15:02:32.771 INFO 42367 --- [ main] o.s.ui.freemarker.SpringTemplateLoader : SpringTemplateLoader for FreeMarker: using resource loader [org.springframework.context.annotation.AnnotationConfigApplicationContext@2aafb23c: startup date [Thu Aug 01 15:02:32 CST 2019]; root of context hierarchy] and template loader path [classpath:/templates/]
2019-08-01 15:02:32.773 INFO 42367 --- [ main] c.l.m.s.SpringBootMailApplication : true-[a, b, c]
2019-08-01 15:02:32.922 INFO 42367 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
网友评论