如果启动了springboot应用程序,则会显示徽标/横幅。我在banner.txt文件中使用了我自己的彩色横幅。它在开始时显示,一切正常。
但我想重复我的横幅后,成功或不成功启动作为上次启动信息。如: Banner +“run”或Banner + "do not run“。
如下所示:
public static void main( String[] args )
{
try {
SpringApplication.run( ControllerUndMain.class, args );
showLogo();
System.out.println('runs')
} catch(Exception e){
showLogo();
System.out.println('not working')
}
}
这有助于我们的管理员和devops查看启动阶段是否结束,以及应用程序是否运行。
问:如何以编程方式显示banner?
发布于 2018-06-30 10:22:28
我找不到任何直接的方法来做这件事。我研究了一下spring代码库,找到了这样做的方法。我已经在我的项目中进行了测试,它工作正常。
注意:我已经复制了spring用来打印banner的一些类。我不认为在我们的代码库中重用有任何问题。
这是一段完整的代码...
运行springboot应用程序的主类,我已经创建了打印banner的方法。
public class DemoApplication {
@Autowired
private Environment env;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(DemoApplication.class);
ConfigurableApplicationContext test = app.run(args);
DemoApplication application = new DemoApplication();
application.printBanner(app, test);
}
public void printBanner(SpringApplication app, ConfigurableApplicationContext test) {
ResourceLoader resourceLoader = (app.getResourceLoader() != null ? app.getResourceLoader()
: new DefaultResourceLoader(app.getClassLoader()));
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, null);
Banner banner = bannerPrinter.print(DemoApplication.class, test.getEnvironment());
banner.printBanner(test.getEnvironment(), DemoApplication.class, System.out);
}
}
添加上述代码库后,只需在项目中复制SpringApplicationBannerPrinter和SpringBootBanner类(您将从Spring代码库获得这些类)并运行即可。
注意: 1)我在这里设置答案之前已经测试过了。2)简而言之,我没有粘贴SpringApplicationBannerPrinter和SpringBootBanner。如果您希望我粘贴这些类作为回答,请让我知道
发布于 2018-07-03 05:06:36
@SpringBootApplication
public class SimpleDemoApplication {
public static void main(String[] args) {
final SpringApplication app;
final ConfigurableApplicationContext context;
app = new SpringApplication(SimpleDemoApplication.class);
context = app.run(args);
print(context);
}
public static void print(ConfigurableApplicationContext context) {
Banner banner = context.getBean(Banner.class);
banner.printBanner(context.getEnvironment(), SimpleDemoApplication.class, System.out);
}
}
只需注入或改写context.getBean org.springframework.boot.Banner.class。这对好的情况有帮助,如果一切都很好,并且上下文是向上的。
如果上下文没有运行,我对最坏的情况没有解决方案。
https://stackoverflow.com/questions/51113265
复制相似问题