Vra

Wanneer ek skryf 'n bevel Lente lyn program wat command line argumente ontleed, hoe kan ek slaag hulle tot die lente? Sou ek wil hê my main () so gestruktureer dat dit die eerste keer die command line argumente ontleed en dan inits Lente? Net so is, hoe sou dit slaag die voorwerp wat die Geperste args tot lente?

Was dit nuttig?

Oplossing

Twee moontlikhede waaraan ek kan dink.

1) Stel 'n statiese verwysing. (A statiese veranderlike, alhoewel tipies afgekeur, is OK in hierdie geval, omdat daar net 1 command line aanroeping kan wees).

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

Jy kan dan verwys na die command line argumente in die lente via:

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

As alternatief (as jy heeltemal gekant teen statiese veranderlikes), kan jy:

2) Programmeer die argumente toe te voeg tot die aansoek konteks:

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

 }

ontleding van die command line argumente het oorgebly soos 'n oefening om die leser.

Ander wenke

Het jy 'n blik op my lente-CLI biblioteek - by http://github.com/sazzer/spring -cli - as een manier om dit te doen. Dit gee jou 'n groot klas wat outomaties laai lente konteks en het die vermoë om Commons-CLI gebruik vir die ontleding van command line argumente outomaties en spuit dit in jou boontjies.

Jy kan ook slaag 'n voorwerp reeks as 'n tweede parameter om getBean wat gebruik sal word as argumente om die konstruktor of fabriek.

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

Vanaf die lente 3.1 Dit is nie nodig in enige persoonlike kode in ander antwoorde voorgestel. Check CommandLinePropertySource dit bied 'n natuurlike manier om CL argumente te spuit in jou konteks.

En as jy 'n gelukkige lente Boot ontwikkelaar kan jy jou kode 'n stap vorentoe gebruik te maak van die feit dat 'n href <= "http://docs.spring.io/spring-boot/docs/current/api/org vereenvoudig /springframework/boot/SpringApplication.html "rel =" nofollow noreferrer "> SpringApplication gee jou die volgende:

  

Deur verstek klas sal die volgende stappe uit te voer om selflaai jou   aansoek:

     

...

     

Registreer n CommandLinePropertySource om command line argumente ontbloot   as die lente eienskappe

As jy belangstel in die lente Boot eiendom resolusie orde is raadpleeg hierdie bladsy .

Oorweeg die volgende klas:

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

}

saam met:

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

}

Hier is 'n voorbeeld vir band lente boot vir 'n Hoof metode, net die afgelope params as normale dan die funksie wat jy 'n beroep op jou boontjie maak (in die geval deployer.execute ()) gryp neem hulle as Strings of via enige formaat jy voel geskik is.

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;
}
Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top