Spring console application configured using annotations

Take a look at the Spring Reference, 3.2.2 Instantiating a container.

In order to use Spring in console application you need to create an instance of ApplicationContext and obtain Spring-managed beans from it.

Creating a context using XML config is described in the Reference. For completely annotation-based approach, you can do someting like this:

@Component // Main is a Spring-managed bean too, since it have @Autowired property
public class Main {
    @Autowired SampleService sampleService;
    public static void main(String [] args) {
        ApplicationContext ctx = 
            new AnnotationConfigApplicationContext("package"); // Use annotated beans from the specified package

        Main main = ctx.getBean(Main.class);
        main.sampleService.getHelloWorld();
    }
}

Leave a Comment

tech