Spring console application configured using annotations

后端 未结 7 1939
谎友^
谎友^ 2021-01-30 13:33

I want to create spring console application (running from command line with maven for example: mvn exec:java -Dexec.mainClass=\"package.MainClass\").

Is this application

7条回答
  •  萌比男神i
    2021-01-30 14:10

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

提交回复
热议问题