Invalid SpringApplication setBanner problem

Two following code snippet:

Fragment 1

1 SpringApplication application = new SpringApplication(SpringBootLearnApplication.class);
2 application.setBanner((environment, sourceClass, out) -> System.out.println("测试banner的设置"));
3 application.run(args);

Fragment 2

1 SpringApplication application = new SpringApplication();
2 application.setBanner((environment, sourceClass, out) -> System.out.println("测试banner的设置"));
3 application.run(SpringBootLearnApplication.class, args);

Difference in the two code snippets then passed inside SpringApplication constructor, or by passing the run this process.

The fragment approach 2, the incoming run method, SpringBootLearnApplication.class this class, exactly the same setBanner cause failure.

We point to open the run method segment 1:

You can see the run method is a member method of entering SpringApplication, that we instantiate the SpringApplication, and calls the run method of this instance.

We then opening segment run method 2:

And a very clear distinction fragment, which is a static method run. And internal methods and new SpringApplication the run time and call the method.

So, fragment 2 actually creates two instances of SpringApplication, setBanner method but on their own instantiated SpringApplication example set, resulting in setBanner last no effect.

We can use the fragment written, it will not appear twice instantiated

1 SpringApplication application = new SpringApplication(SpringBootLearnApplication.class);
2 application.setBanner((environment, sourceClass, out) -> System.out.println("测试banner的设置"));
3 application.run(args);

Or, if absolutely no need to set anything directly abbreviated default

1 SpringApplication.run(SpringBootLearnApplication.class, args);

不论如何最终都将按照这样的顺序执行new SpringApplication() --> run()

 

Guess you like

Origin www.cnblogs.com/lay2017/p/11408537.html