Spring - 在运行时提供@Autowired

时间:2016-10-03 14:55:03

标签: java spring web-services

实际上,我有一个程序被另一个Web服务称为Web服务。我的程序的调用者将输入(也是我的程序的输入)转换为JSON,然后调用我的程序,传入JSON。我的程序将它(通过GSON)转换为Java代码。请记住,输入位于我的pom中包含的jar文件中。有没有办法自动连接部分输入?

到目前为止,我所做的是将@Component置于我想要自动装配的部分,称为SystemInfo:

@Component
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>

我已经设置了一个包含以下内容的ApplicationConfig.java:

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

}

我把它放在罐子里所以它会看到@Component。我为我的程序输入了xml:

<bean id="systemInfo"
    class="org.mhcd.avatar.model.domainLayer.SystemInfo"
    autowire="byType" autowire-candidate="true">
</bean>

然后,我加入了我的程序:

@Autowired
private ApplicationContext context;

GenericApplicationContext ctx = new GenericApplicationContext(context);
ctx.refresh();

我将JSON转换为Java对象后的刷新。我将@Autowired放在我的DAO对象的SystemInfo前面,然后我在调试中逐步执行了我的DAO,SystemInfo为null。我认为必须有办法做到这一点,但我不知道它是什么。

1 个答案:

答案 0 :(得分:0)

我终于放弃了几乎所有的Spring注释。我仍然有@RestController,有些@Component,还有@Autowired@Repository。我把这个放在我的所有DAO中解决了这个问题:

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

然后在做任何工作之前调用init方法,提供systemInfo作为参数。

必须有一些方法可以做@Autowired类似的事情,但我不知道它是什么。

相关问题