简体   繁体   中英

Initializing a spring bean with command line arguments

What is the best way to map command line parameters to an object from the main class, and then access them from another class? I have tried with the below, but get an error message: Non-static method cannot be referenced from a static context . As it's not possible for me to make the methods in AppConfig static, what else can I do?

I am trying to initialise a spring bean with command line arguments and this is one way I thought of doing it.

I've just seen I can do what I need for now using a singleton to hold the values before instantiating the beans, and referencing the singleton in the bean. Although this sounds obvious I cannot for the life of me see how to do this with an annotated class. What can I try next?

Launcher.java

public class Launcher {

   public static void main(String [] args) throws Throwable {
       AppConfig appConfig = new AppConfig();
       appConfig.setParam1(args[0]);
       appConfig.setParam2(args[1]); 
       
       AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);
       ...
   }

}

AppConfig.java

public class AppConfig {
       private String param1;
       private String param2;                

       public String getParam1() {
             return param1;
       }

       public String setParam1(String param1) {
             this.param1 = param1;
       }

       public String getParam2() {
             return param2;
       }

       public String setParam2(String param2) {
             this.param2 = param2;
       }
}

AppContext.java

@Configuration
@ComponentScan(basePackageClasses = Launcher.class)
@Slf4j
public class AppContext {
       AppConfig appConfig = new AppConfig();

       private final String PARAM_1 = appConfig.getParam1();  
       private final String PARAM_2 = appConfig.getParam2();                 
}

The alternative for me is to re-instantiate the class again within AppContext, but does that mean I lose access to the command line arguments getting passed through:

@Configuration
@ComponentScan(basePackageClasses = Launcher.class)
@Slf4j
public class AppContext {
       

       private final String PARAM_1 = AppConfig.getParam1();  
       private final String PARAM_2 = AppConfig.getParam2();                 
}

The way you're using private final String PARAM_1 = AppConfig.getParam1(); requires that the method String getParam1() MUST be static. Although I do not see it as usual approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM