SpringBoot随笔1
@SpringBootApplication注解
package com.example.myapplication;
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);
}
}
@SpringBootApplication注解用来标识你的主类,如果不想使用该注解,官方提出可以使用@EnableAutoConfiguration 和 @ComponentScan和@Configuration组合来代替,也可以实现相同的功能!
@EnableAutoConfiguration:开启自动配置
@ComponentScan:扫描组件
@Configuration: 允许在上下文中注册额外的 bean 或者导入额外的配置类
If you don’t want to use @SpringBootApplication, the @EnableAutoConfiguration and @ComponentScan annotations that it imports defines that behaviour so you can also use those instead.
2、Spring官方建议的包结构如下:
3、导入额外的配置类
You need not put all your @Configuration into a single class. The @Import annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan to automatically pick up all Spring components, including @Configuration classes.
意思就是我们没有必要将所有的自定义的配置类都放在一个类里面,可以搞好几个类,然后使用@Import注解导入,也可以使用@ComponentScan注解进行批量导入。
4、导入 XML 配置
If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an @ImportResource annotation to load XML configuration files.
如果我们需要用到XML配置文件进行Bean的声明和配置,我们就可以使用@ImportResource注解来把XMl的Bean导入到SpringBoot容器中。
5、自动配置
如果想知道SpringBoot在启动的时候都自动配置了哪些应用,可以开启debug调试进行查看
f you need to find out what auto-configuration is currently being applied, and why, start your application with the —debug switch. Doing so enables debug logs for a selection of core loggers and logs a conditions report to the console.
可以使用java -jar app —debug
也可以在配置文件中加入debug=true即可
6、禁用特定的自动配置类
由于SpringBoot启动的时候会自动配置很多类,如果有你不想使用的类,可以选择排除不加载
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
@SpringBootApplication(exclude={ DataSourceAutoConfiguration.class})
public class MyApplication {
}
如果这个类不在当前类路路径下,你还可以使用excludeName 来指定其类的完全限定名
7、自动重启
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
加入devtools依赖,在类路径下的代码发生改变以后,点击IDEA的build–build project可以在不重启项目的情况下更改的代码自动生效
8、惰性加载
spring.main.lazy-initialization=true 控制所有的bean延迟加载
如果想为特定Bean指定延迟加载 可以使用@Lazy注解
9.自定义Springboot启动图标
在类路径下放banner.txt/banner.png/gif 等文件,再次重启即可生效
10.关闭Banner
public static void main(String[] args) {
SpringApplication app = new SpringApplication(DemoApplication.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
还没有评论,来说两句吧...