一.容器启动执行两种实现。
第一种: applicationrunner
package com.hangzhou.runner;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
//容器启动之后,执行一些操作
@Order(value=2)
@Component
public class runner02 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Running runner02");
}
}
第二种:CommandLineRunner
/**
*
*/
/**
* @author Administrator
*
*/
package com.hangzhou.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(value=1)
@Component
public class runner01 implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println("running eunner01");
}
}
注:默认第一先执行。但可以@order设置执行顺序,小的执行。还有他们的方法传参不同,待续。。。。
二.读取配置文件生成Bean。 @ConfigurationProperties(prefix="adconf.mysql")
package com.hangzhou.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 读配置文件
* @author Administrator
*
*/
@Component
@ConfigurationProperties(prefix="adconf.mysql")
public class MySQLConfig {
private String host;
private Integer port;
private String username;
private String password;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
配置文件
spring:
profiles:
active: prod
adconf:
mysql:
host:127.0.0.1
port:3306
username:root
password:Djangobbs
spring:
profiles:dev
server:
port:8080
spring:
profiles:test
server:
port:8081
还可以设置配置环境切换spring.profiles.active=test
三.定时任务。
package com.hangzhou.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 定时任务
* @author Administrator
*
*/
@Component
public class ScheduledTask{
/**@Scheduled(fixedRate=1000) 上次开始执行时间点之后5秒再执行
* @Scheduled(fixedDelay=1000) 上次执行完毕时间点之后5秒再执行
*/
//@Scheduled(cron="*/5 * * * *") 通过crontab 表达式定义规则
@Scheduled(fixedRate=1000)
public void helloSpring() {
System.out.println("hello springBoot");
}
}
要开启定时功能
package com.hangzhou.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class SpringBootStudy{
public static void main(String[] args) {
SpringApplication.run(SpringBootStudy.class, args);
}
}
待续。。。。。