第十四天,7月8日,八股
1、如何在Spring boot启动时运行一些特定的代码
就是如何把自定义的类(调度器的任务类)加入到Spring生命周期
(1)接口ApplicationRunner或者CommandLineRunner这个两个接口都只提供了一个run方法,实现上述接口的类加入ioc即可生效
(2)使用@PostConstruct注解,即可在bean初始化后立刻执行代码
2、如何重新加载Spring Boot上的更新,而无需重新启动服务器
就是如何实现热部署
使用开发工具dettools,添加依赖spring-boot-devtools即可,但是该模式在生产环境中禁用
3、RequestMapping和GetMapping的不同之处在哪里
SpringMVC中最常用的注解,可以处理http请求
(1)RequestMapping具有类属性(可以标注在类上),可以进行get、post、put或者delete等
(2)GetMapping是Get请求方法的一个特例,是RequestMapping的一个延伸(@RequestMapping(method = RequestMethod.GET)),目的是为了提高清晰度
4、Spring Boot需要独立的容器运行吗
可以不需要,内置了Tomcat/jetty(轻量级的web服务器和servlet容器)等容器
5、Spring Boot支持哪些日志框架,推荐和默认哪个日志看框架
(1)支持logback,log4j2和java util logging(jul)
(2)如果使用了‘starter’,默认是logback
6、Spring boot有哪几种读取配置的方式
(1)@Value(${a.b}):适合读取单个配置项,不适合批量读取
(2) @ConfigurationProperties(prefix='a'):适合批量读取配置项,并将其注入到POJO类中
(3)@PropertySouce("classpath:a.properrties")+@Value("${}"):加载自定义的properties文件,并读取其中的属性值
(4)使用Environment接口:
@RestController
public class MyController {
@Autowired
private Environment environment;@RequestMapping("/property")
public String getProperty() {
return environment.getProperty("my.property");
}
}
(5)java原生方式
public class MyConfig {
public static void main(String[] args) throws IOException {
Properties props = new Properties();
try (InputStream input = new FileInputStream("my.properties")) {
props.load(input);
}
System.out.println(props.getProperty("my.property"));
}
}
7、Spring Boot如何定义多套不同环境配置
(1)基于properties配置文件
【1】创建各环境的配置文件:application.properties、application-dev.properties、application-test.properties、application-prod.properties
【2】在application.properties中指定配置文件,spring-profiles.active=test
(2)基于yml文件
可以只需要一个application.yml文件即可
# application.yml
spring:
profiles:
active: prod---
spring:
profiles: dev
server:
port: 8083---
spring:
profiles: prod
server:
port: 8084
8、Spring Boot可以兼容老Spring项目吗
可以兼容,使用@ImportResource注解注入老Spring项目配置文件