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

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.


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.


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.


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);

        ...
        ...
    }
}