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

前端 未结 5 2060
广开言路
广开言路 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);
    
            ...
            ...
        }
    }
    
    0 讨论(0)
  • 2021-02-07 13:03

    You can perform DI on any instance, whether Spring managed or created with new.

    To do so, use the following code...

    AutowireCapableBeanFactory awcbf = applicationContext.getAutowireCapableBeanFactory();
    awcbf.autowireBean(yourInstanceCreatedWithNew);
    

    This is also a great way to introduce Spring into an application that was developed originally without Spring - as it allows you to use Spring where you want it without having to convert every class in the application into a Spring bean (because typically, you can't use a Spring bean without a Spring bean).

    0 讨论(0)
  • 2021-02-07 13:10

    When you create an object by new, autowire\inject don't work...

    as workaround you can try this:

    create your template bean of NotesPanel

    <bean id="notesPanel" class="..." scope="prototype">
        <!-- collaborators and configuration for this bean go here -->
    </bean>
    

    and create an istance in this way

    context.getBean("notesPanel");
    

    PROTOTYPE : This scopes a single bean definition to have any number of object instances.

    0 讨论(0)
  • 2021-02-07 13:14

    Spring support @Autowire, ... only for Spring Beans. Normally a Java Class become a Spring Bean when it is created by Spring, but not by new.

    One workarround is to annotate the class with @Configurable but you must use AspectJ (compile time or loadtime waving)!

    @see Using Spring's @Configurable in three easy steps for an short step by step instruction.

    0 讨论(0)
  • 2021-02-07 13:16

    The problem is here:

    frame.add(new NotesPanel(), BorderLayout.CENTER);

    you are creating a new object for class NotesPanel in the constructor of class Notepad.

    The constructor is called before method main, so Spring context has not been loaded yet.

    When instantiating the object for NotesPanel, it can't auto wire BackgroundGray because Spring context doesn't exists at that moment.

    0 讨论(0)
提交回复
热议问题