Spring boot Autowired in JFrame

2

When developing a Spring Boot Desktop application, can you inject a @Repository into a JFrame class?

If yes how? Any alternative?

Code samples:

@Repository
public interface ItemRepository extends CrudRepository<Item, Long> {}

public class ItemFrame extends JFrame {

    @Autowired
    private ItemRepository repository;

}

This code gives NullPointerException , I already tried to annotate the class with @Component and @Controller but on success.

Here is an example of the main class.

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class);
        new ItemFrame().setVisible(true);
    }
}
    
asked by anonymous 15.07.2016 / 02:43

1 answer

1

Spring will not manage instances created with new! Spring itself must create the class instance for the injections to work. The right one would be to inject the itemFrame object through Spring as well, but since the main method is static we can not inject with @Autowired. An alternative is to get the instance created by Spring through ApplicationContext as follows:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
    ApplicationContext context = new SpringApplicationBuilder(MyApplication.class)
    .headless(false).run(args);
    ItemFrame a = context.getBean(ItemFrame.class);
    a.setVisible(true);
    }
}

When you annotate a class with @Component, @Service, @Repository or @Controller Spring creates an instance of this class by calling its constructor without parameters or the constructor annotated with @Autowired if it exists. When you create it, it injects all its dependencies correctly and the instance gets into your ApplicationContext. Classes created with new will not be managed by Spring, unless you put them in the application context manually.

In addition, to run with Spring Boot you should put the .headless (false) option. Also, the ItemFrame class must be annotated with @Component in order to be injected.

@Component
public class ItemFrame extends JFrame{
    ...
}
    
26.07.2016 / 13:33