首页 > 解决方案 > How to convert plain java main method program on docker

问题描述

public class SIIRunner {   

    public static void main(String[] args){   

        String envStr = null;
        if (args != null && args.length > 0) {
            envStr = args[0];
        }

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        SIIExecutor siiExecutor= (SIIExecutor) ctx.getBean("SIIExecutor");
        siiExecutor.pollAndOperate();
    }
}

标签: spring-bootdocker

解决方案


@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        ApplicationContext app = SpringApplication.run(Application.class, 
         args);//init the context
        SIIExecutor siiExecutor = (SIIExecutor) 
         app.getBean(SIIExecutor.class);//get the bean by type
    }
    @Bean // this method is the equivalent of the <bean/> tag in xml
    public SIIExecutor getBean(){
         return new SIIExecutor();
    }
}

As long as you are starting with a base @Configuration class to begin with, which it maybe sounds like you are with @SpringBootApplication, you can use the @ImportResource annotation to include an XML configuration file as well.

@SpringBootApplication
@ImportResource("classpath:beanFileName.xml")
public class SpringConfiguration {
  //
}

Spring boot ideal concept is avoid xml file. but if you want to keep xml bean, you can just add @ImportResource("classPath:beanFileName.xml")

I would recommend remove the beanFileName.xml file. and, convert this file to spring annotation based bean. So, whatever class has been created as bean. Just write @Service or @Component annotation before class name. for example:

XML based:

<bean ID="id name" class="com.example.MyBean">

Annotation based:

@Service or @Component
class MyBean {
}

And, add @ComponentScan("Give the package name").

This is the best approach. Hope this helps.


推荐阅读