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

前端 未结 2 823
傲寒
傲寒 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;
        }
    

提交回复
热议问题