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