Why does Swing think it's headless under Spring Boot, but not under Spring or plain Java?

前端 未结 2 824
傲寒
傲寒 2021-01-17 10:22

The following code works:

import javax.swing.*;

public class HeadlessExceptionDemo {

   public static void main(String[] args) {

      JFrame frame = new          


        
相关标签:
2条回答
  • 2021-01-17 10:29

    Spring Boot sets java.awt.headless to true by default as seen in the source code for SpringApplication.java:

    private boolean headless = true;
    
    ...
    
    private void configureHeadlessProperty() {
            System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty(
                    SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
    }
    

    As to why it does this, there is a comment in the source code on the setHeadless method about preventing icons from appearing:

        /**
         * Sets if the application is headless and should not instantiate AWT. Defaults to
         * {@code true} to prevent java icons appearing.
         * @param headless if the application is headless
         */
        public void setHeadless(boolean headless) {
            this.headless = headless;
        }
    
    0 讨论(0)
  • 2021-01-17 10:36

    instead of this line

     SpringApplication.run(Application.class, args);
    

    use

    SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
    builder.headless(false);
    ConfigurableApplicationContext context = builder.run(args);
    
    0 讨论(0)
提交回复
热议问题