복붙노트

[SPRING] 커맨드 라인 인자와 스프링 다루기

SPRING

커맨드 라인 인자와 스프링 다루기

명령 줄 인수를 구문 분석하는 Spring 명령 줄 응용 프로그램을 작성할 때 Spring에 전달하는 방법은 무엇입니까? main ()을 구조화하여 명령 행 인수를 먼저 구문 분석 한 다음 봄에 삽입하도록하고 싶습니까? 그럼에도 불구하고, 파싱 된 인자를 가지고있는 객체를 Spring으로 어떻게 넘겨 줄 것인가?

해결법

  1. ==============================

    1.내가 생각할 수있는 두 가지 가능성.

    내가 생각할 수있는 두 가지 가능성.

    1) 정적 참조를 설정합니다. (정적 변수는 일반적으로 frown 된 것이지만이 경우에는 1 개만 명령 행을 호출 할 수 있기 때문에 OK입니다.)

    public class MyApp {
      public static String[] ARGS; 
      public static void main(String[] args) {
        ARGS = args;
          // create context
      }
    }
    

    그런 다음 Spring을 통해 명령 행 인수를 참조 할 수 있습니다.

    <util:constant static-field="MyApp.ARGS"/>
    

    또는 (정적 변수에 완전히 반대되는 경우) 다음을 수행 할 수 있습니다.

    2) 프로그래밍 방식으로 args를 응용 프로그램 컨텍스트에 추가합니다.

     public class MyApp2 {
       public static void main(String[] args) {
         DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    
            // Define a bean and register it
         BeanDefinition beanDefinition = BeanDefinitionBuilder.
           rootBeanDefinition(Arrays.class, "asList")
           .addConstructorArgValue(args).getBeanDefinition();
         beanFactory.registerBeanDefinition("args", beanDefinition);
         GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);
         // Must call refresh to initialize context 
         cmdArgCxt.refresh();
    
         // Create application context, passing command line context as parent
         ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt);
    
         // See if it's in the context
         System.out.println("Args: " + mainContext.getBean("args"));
       }
    
       private static String[] CONFIG_LOCATIONS = new String[] {
         "applicationContext.xml"
       };
    
     }
    

    명령 행 인수를 구문 분석하는 것은 독자에게 연습으로 남겨 둡니다.

  2. ==============================

    2.이것을 수행하는 한 가지 방법으로 http://github.com/sazzer/spring-cli에있는 Spring-CLI 라이브러리를 살펴보십시오. 그것은 자동적으로 봄 문맥을로드하고 커맨드 라인 인자를 자동으로 파싱하고 콩에 주입하는 Commons-CLI를 사용할 수있는 메인 클래스를 제공합니다.

    이것을 수행하는 한 가지 방법으로 http://github.com/sazzer/spring-cli에있는 Spring-CLI 라이브러리를 살펴보십시오. 그것은 자동적으로 봄 문맥을로드하고 커맨드 라인 인자를 자동으로 파싱하고 콩에 주입하는 Commons-CLI를 사용할 수있는 메인 클래스를 제공합니다.

  3. ==============================

    3.생성자 또는 팩토리에 대한 인수로 사용될 getBean의 두 번째 매개 변수로 Object 배열을 전달할 수도 있습니다.

    생성자 또는 팩토리에 대한 인수로 사용될 getBean의 두 번째 매개 변수로 Object 배열을 전달할 수도 있습니다.

    public static void main(String[] args) {
       Mybean m = (Mybean)context.getBean("mybean", new Object[] {args});
    }
    
  4. ==============================

    4.Spring 3.1부터는 다른 답변에서 제안 된 맞춤 코드가 필요 없습니다. CommandLinePropertySource를 확인하면 CL 인수를 컨텍스트에 삽입하는 자연스러운 방법을 제공합니다.

    Spring 3.1부터는 다른 답변에서 제안 된 맞춤 코드가 필요 없습니다. CommandLinePropertySource를 확인하면 CL 인수를 컨텍스트에 삽입하는 자연스러운 방법을 제공합니다.

    그리고 운이 좋은 Spring Boot 개발자라면 SpringApplication에서 다음과 같은 사실을 활용하여 코드를 한 단계 앞당길 수 있습니다.

    Spring Boot 속성 해결 순서에 관심이 있다면이 페이지를 참조하십시오.

  5. ==============================

    5.다음 클래스를 고려하십시오.

    다음 클래스를 고려하십시오.

    public class ExternalBeanReferneceFactoryBean 
        extends AbstractFactoryBean
        implements BeanNameAware {
    
        private static Map<String, Object> instances = new HashMap<String, Object>();
        private String beanName;
    
        /**
         * @param instance the instance to set
         */
        public static void setInstance(String beanName, Object instance) {
            instances.put(beanName, instance);
        }
    
        @Override
        protected Object createInstance() 
            throws Exception {
            return instances.get(beanName);
        }
    
        @Override
        public Class<?> getObjectType() {
            return instances.get(beanName).getClass();
        }
    
        @Override
        public void setBeanName(String name) {
            this.beanName = name;
        }
    
    }
    

    와 함께:

    /**
     * Starts the job server.
     * @param args command line arguments
     */
    public static void main(String[] args) {
    
        // parse the command line
        CommandLineParser parser = new GnuParser();
        CommandLine cmdLine = null;
        try {
            cmdLine = parser.parse(OPTIONS, args);
        } catch(ParseException pe) {
            System.err.println("Error parsing command line: "+pe.getMessage());
            new HelpFormatter().printHelp("command", OPTIONS);
            return;
        }
    
        // create root beanFactory
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    
        // register bean definition for the command line
        ExternalBeanReferneceFactoryBean.setInstance("commandLine", cmdLine);
        beanFactory.registerBeanDefinition("commandLine", BeanDefinitionBuilder
            .rootBeanDefinition(ExternalBeanReferneceFactoryBean.class)
            .getBeanDefinition());
    
        // create application context
        GenericApplicationContext rootAppContext = new GenericApplicationContext(beanFactory);
        rootAppContext.refresh();
    
        // create the application context
        ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { 
            "/commandlineapp/applicationContext.xml"
        }, rootAppContext);
    
        System.out.println(appContext.getBean("commandLine"));
    
    }
    
  6. ==============================

    6.다음은 Main 메소드 용 스트랩 스프링을 부팅하는 예제입니다. 전달 된 매개 변수를 정상적으로 가져온 다음 bean에서 호출하는 함수 (예 : deployer.execute ())를 String 또는 적합한 형식으로 가져옵니다 .

    다음은 Main 메소드 용 스트랩 스프링을 부팅하는 예제입니다. 전달 된 매개 변수를 정상적으로 가져온 다음 bean에서 호출하는 함수 (예 : deployer.execute ())를 String 또는 적합한 형식으로 가져옵니다 .

    public static void main(String[] args) throws IOException, ConfigurationException {
        Deployer deployer = bootstrapSpring();
    
        deployer.execute();
    }
    
    private static Deployer bootstrapSpring()
    {
        FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("spring/deployerContext.xml");
    
        Deployer deployer = (Deployer)appContext.getBean("deployer");
        return deployer;
    }
    
  7. from https://stackoverflow.com/questions/132231/dealing-with-command-line-arguments-and-spring by cc-by-sa and MIT license