horndinkle horndinkle - 1 year ago 142
Java Question

Spring - Providing @Autowired at runtime

I have a program that's being called as a web service, from another web service, actually. The caller of my program converts the input (which is the input to my program too) to JSON, and then calls my program, passing the JSON in. My program converts it (through GSON) to Java code. Keep in mind that the input is in a jar file that's included in my pom. Is there a way to autowire a part of the input?

What I've done so far is to put

on the part I want to autowire, called SystemInfo:

public class SystemInfo {
protected String GUID;
protected String EntityID;
protected Double EpisodeNumber;
protected Double ErrorCode;
protected String ErrorMesg;
protected String Facility;
protected String NamespaceName;
protected String OptionId;
protected String OptionStaffId;
protected String OptionUserId;
protected String ParentNamespace;
protected String ServerName;
protected String SystemCode;
protected String WarName;
protected String ScriptName;

* @return the gUID
public String getGUID() {
return GUID;
<other setters and getters>

I've set up an ApplicationConfig.java that consists of:

@ComponentScan(basePackages = "org.mhcd.avatar.model")
public class ApplicationConfig {


I put that in the jar so it would see the
. I put in the xml for my program:

<bean id="systemInfo"
autowire="byType" autowire-candidate="true">

Then, I put in my program:

private ApplicationContext context;


GenericApplicationContext ctx = new GenericApplicationContext(context);

The refresh I put after I converted the JSON to Java objects. I put
in front of the SystemInfo in my DAO objects, and I stepped through my DAOs in debug, and SystemInfo is null. I'm thinking there must be a way to do this, but I don't know what it is.

Answer Source

I finally gave up and took out almost all the Spring annotations. I still have @RestController, some @Component, and a sprinkling of @Autowired and @Repository. I got around this issue by putting this in all my DAOs:

private SystemInfo systemInfo;
public void init(SystemInfo systemInfo) {
    this.systemInfo = systemInfo;

I then called the init method before doing any work, providing systemInfo as an argument.

There must be some way to do this as an @Autowired sort of thing, but I don't know what it is.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download