2019年java中高级java面试题(四)springBoot

1、如何在 Spring Boot 启动的时候运行一些特定的代码?

可以实现接口 ApplicationRunner 或者 CommandLineRunner,这两个接口实现方式一样,它们都只提供了一个 run 方法

@Component
@Order(1)
public class Mytest implements ApplicationRunner {
	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("启动测试");
	}

}
@Component
@Order(1)
public class Mytest implements CommandLineRunner {

	@Override
	public void run(String... args) throws Exception {
		System.out.println("启动测试");
	}
	
}

2、Spring Boot 有哪几种读取配置的方式?


Spring Boot 可以通过 @PropertySource,@Value,@Environment, @ConfigurationProperties 来绑定变量

@PropertySource(value={"classpath:/user.properties"})
public class Configs {
    @Value("${u.name}")
    private String userName;
 
    @Value("${u.age}")
    private Integer age;
}
mail.host=localhost
mail.port=25
mail.smtp.auth=false
mail.smtp.starttls-enable=false
mail.from=me@localhost
mail.username=duan
mail.password=duan123456

 

import org.springframework.boot.context.properties.ConfigurationProperties;
 
@ConfigurationProperties(locations = "classpath:mail.properties", ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
    private String host;
    private int port;
    private String from;
    private String username;
    private String password;
    private Smtp smtp;
 
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章