How to autowire an object in spring in an object created with new

前端 未结 5 2061
广开言路
广开言路 2021-02-07 12:35

all I want to do is autowire the field backgroundGray in the NotesPanel class, but all I get is the exception below.

So, question is, how to autowire it correctly ? It r

5条回答
  •  长情又很酷
    2021-02-07 13:02

    I share with you an example. I hope you love it :)

    public class Main {
        public static void main(String args[]) {
    
    
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        UIManager
                                .setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    new Ihm().setVisible(true);
                }
            });
        }
    }
    

    My configuration bean:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    @Configuration
    @ComponentScan("com.myproject.configuration")
    @PropertySource("classpath:/application.properties")
    public class Config {
    
        @Bean
        public Configurator configurator() {
            return new Configurator();
        }
    
    }
    

    My java swing ihm that uses my configuration bean:

    public class Ihm extends JFrame {
    
        private MyConfiguration configuration;
    
        public SmartRailServerConfigurationFileIhm() {
    
            try {
                ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
                configurator = context.getBean(MyConfiguration.class);
            } catch (Exception ex) {
    
            }
            System.out.println(configuration);
    
            ...
            ...
        }
    }
    

提交回复
热议问题