문제

명령 줄 인수를 구문 분석하는 스프링 명령 줄 응용 프로그램을 작성할 때 어떻게 스프링으로 전달합니까? 먼저 명령 줄 Args를 구문 분석 한 다음 스프링을 이용할 수 있도록 내 메인 ()을 구성하고 싶습니까? 그럼에도 불구하고, 구문 분석 된 Args를 봄으로 잡는 물체를 어떻게 통과합니까?

도움이 되었습니까?

해결책

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

1) 정적 참조를 설정하십시오. (정적 변수는 일반적으로 눈살을 찌푸 렸지만이 경우에는 괜찮습니다.

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

그런 다음 다음을 통해 봄에 명령 줄 인수를 참조 할 수 있습니다.

<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"
   };

 }

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

다른 팁

내 Spring -CLI 라이브러리를 살펴보십시오 http://github.com/sazzer/spring-cli - 이것을하는 한 가지 방법으로. 그것은 당신에게 스프링 컨텍스트를 자동으로로드하고 명령 줄 인수를 자동으로 구문 분석하고 콩에 주입 할 수있는 메인 클래스를 제공합니다.

객체 배열을 두 번째 매개 변수로 전달할 수도 있습니다. getBean 이는 생성자 또는 공장에 대한 인수로 사용됩니다.

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

봄부터 시작하여 3.1 다른 답변에서 제안 된 사용자 정의 코드는 필요하지 않습니다. 확인하다 CommandLinePropertySource, 그것은 당신의 맥락에 CL 인수를 주입하는 자연스러운 방법을 제공합니다.

그리고 행운의 스프링 부츠 개발자라면 코드를 한 단계 더 단순화하여 사실을 활용할 수 있습니다. Sprispplication 다음을 제공합니다.

기본적으로 클래스는 다음 단계를 수행하여 응용 프로그램을 부트 스트랩합니다.

...

명령 줄 인수를 스프링 속성으로 노출시키기 위해 CommandLinePropertySource 등록

그리고 Spring Boot Property Resolution 주문에 관심이 있으시면 문의하십시오. 이 페이지.

다음 수업을 고려하십시오.

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"));

}

다음은 기본 메소드를 위해 스트랩 스프링을 부팅하는 예입니다. 전달 된 매개 변수를 정상적으로 잡고 Bean에서 호출하는 기능 (Case Deployer.Execute ())를 문자열로 사용하거나 적합한 형식을 통해 사용하십시오. .

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top