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;
 
}


 

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