gpt4 book ai didi

java - 如何在没有 Controller 的情况下运行@SpringBootApplication

转载 作者:行者123 更新时间:2023-11-30 05:48:54 25 4
gpt4 key购买 nike

如何使用@SpringBootApplication注释从类运行代码。我想运行我的代码而不调用 Controller 并从终端而不是网络浏览器获取信息。我尝试在@SpringBootApplication中调用weatherService,但我的应用程序启动失败,并带有描述

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
| weatherClientApplication
↑ ↓
| weatherService defined in file [C:\Users\xxx\IdeaProjects\weatherclient\target\classes\com\xxx\restapiclient\service\WeatherService.class]
└─────┘
@SpringBootApplication
public class WeatherClientApplication {

private WeatherService weatherService;

public WeatherClientApplication(WeatherService weatherService) {
this.weatherService = weatherService;
}

private static final Logger log = LoggerFactory.getLogger(WeatherClientApplication.class);

public static void main(String[] args) {
SpringApplication.run(WeatherClientApplication.class, args);
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}


@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
log.info(weatherService.getTemperatureByCityName("Krakow"));
};
}

}
@Service
public class WeatherService {

private RestTemplate restTemplate;

public WeatherService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

public String getTemperatureByCityName(String cityName) {
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&APPID=" + API_KEY + "&units=metric";
Quote quote = restTemplate.getForObject(url, Quote.class);
return String.valueOf(quote.getMain().getTemp());
}
}

最佳答案

您可以通过使用 main 方法和 ApplicationContext 来完成此操作,在这种方法中,您不需要任何 CommandLineRunner

public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(WeatherClientApplication.class, args);
WeatherService service = (WeatherService)context.getBean("weatherService");
service. getTemperatureByCityName("cityname");
}

关于java - 如何在没有 Controller 的情况下运行@SpringBootApplication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54315223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com