Spring console application configured using annotations

后端 未结 7 1869
谎友^
谎友^ 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条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 14:09

    Regarding Chin Huang's answer above...

    Your example won't actually work, or at least isn't working for me locally. That's because you're initializing the SampleService object using @Autowired, but you specify AutowireCapableBeanFactory.AUTOWIRE_NO on the properties. Instead set it to AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE or AutowireCapableBeanFactory.AUTOWIRE_BY_NAME.

    Also, this is odd, so I may be doing something wrong. But it seems that with AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, I have to have a setProp() with @Autowired for it to work. So instead of this:

    public class Main {
        @Autowired
        private SampleService sampleService;
    
        public static void main(String[] args) {
            Main main = new Main();
            ApplicationContextLoader loader = new ApplicationContextLoader();
            loader.load(main, "applicationContext.xml");
            main.sampleService.getHelloWorld();
        } 
    }
    

    I have to do this:

    public class Main {
        private SampleService sampleService;
    
        public static void main(String[] args) {
            Main main = new Main();
            ApplicationContextLoader loader = new ApplicationContextLoader();
            loader.load(main, "applicationContext.xml");
            main.sampleService.getHelloWorld();
        } 
    
        @Autowired
        public void setSampleService(SampleService sampleService) {
            this.sampleService = sampleService;
        }
    }
    

    If I have, as in Chin's original example, private data with @Autowired, the DI fails. I'm using 3.1.1.RELEASE and I think some of the auto-wiring stuff has changed in 3.1.x, so it may be due to that. But I'm curious as to why this wouldn't work, since that's consistent with earlier releases of Spring.

提交回复
热议问题