Tim AtLee
Tim AtLee

Reputation: 1009

Spring Boot application, how to pass Java object into application?

I have a GUI that launches a Spring Boot application:

    SpringApplication application = new SpringApplication(ServerSpringApplication.class);
    ConfigurableApplicationContext ctx = application.run(args);

I am trying to pass a reference to the GUI object into the Spring Boot application so the SpringApplication can read values from the GUI object.

I know args is a String[], so I don't think I can pass objects in through the run method.

Alternatively, is there a way that SpringApplication can find a reference to the object that instantiated it?

Thanks for any help and direction.

Upvotes: 0

Views: 974

Answers (1)

Patrick
Patrick

Reputation: 3230

I assume you'd like to do this because the values in the "GUI Object" are going to change, and the Spring Boot application should inherit those values?

As others have noted, this is a bit of an anti-pattern, using Spring to host the GUI or having some other method of communication would be clearer, architecturally. You could get some really odd memory interactions this way.

So, proceed with caution.

If you do want interactions between the main app and SB, the Spring Boot application runs within the same JVM as the application that kicks it off (take note of this, because it means it shares the same heap space, so make sure you have enough allocated). This means that you can use a singleton instance to store the GUI application, and the Spring Boot application would have access to that singleton.

I.e.,

public class MyGuiStorage {
private static MyGuiStorage _instance = null;

//The object SpringBoot should have access to
private static GuiObject myObj = null;

protected MyGuiStorage () {
  // Don't allow public instantiation
}

public static MyGuiStorage getInstance() {
  if( _instance== null) {
      _instance= new MyGuiStorage();
  }
  return instance;
}

public void setGuiObject(GuiObject myObj) {
  this.myObj = myObj;
}

public GuiObject getGuiObject() {
  return myObj;
}
}

Then Spring can access it using MyGuiStorage.getInstance().getGuiObject();

Upvotes: -1

Related Questions