我試圖在服務器啟動時,在一個單獨的執行緒中執行一個方法。下面是我的主類:
@SpringBootApplication
@EnableSwagger2
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args)。
}
@Bean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor()。
}
@Bean[/span
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
return new CommandLineRunner(){
public void run(String... args) throws Exception {
executor.executor(new CsvReader()。
}
};
}
}
@Component
public class CsvReader implements Runnable{
@Value("${file-url}")
private String appUrl;
@Override
public void run {
System.out.println("run after Object created: " appUrl); // this is coming as null. 無法從application.properties中讀取它。
}
}
uj5u.com熱心網友回復:
你可以使用@PropertySource注解。
像這樣
@SpringBootApplication
@PropertySource("application.properties")
@EnableSwagger2
public class Application {
//你的代碼。
}
你可以像這樣自動連接值
public class CsvReader implements Runnable{
private String appUrl;
public void run {
System.out.println("run after Object created: " appUrl); // this is coming as null. 無法從application.properties中讀取它。
}
}
uj5u.com熱心網友回復:
得到的問題是,
由于我在一個單獨的執行緒中執行CsvReader,容器沒有照顧到bean的初始化,因此依賴注入沒有發揮作用。
通過
解決了這個問題@Configuration
public class CsvReader {
@Value("${file-url}")
private String appUrl;
@PostConstruct
private void runAfterObjectCreated() {
Thread thread = new Thread(){
public void run() {
System.out.println("run after Object created: "/span> appUrl)。
}
};
thread.start()。
}
}
通過上述代碼,我將bean的實體化委托給了容器。
@PostConstruct,確保在類被加載后的執行,并且由于我有一個Thread類被實體化,該方法在一個新執行緒中運行。
選項2
@SpringBootApplication
@EnableSwagger2
public class Application {
@Autowired
private CsvReader csvReader;
public static void main(String[] args) {
SpringApplication.run(Application.class, args)。
}
@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
return new CommandLineRunner(){
public void run(String... args) throws Exception {
executor.execute(csvReader)。
}
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/308324.html
標籤:
