【发布时间】:2021-10-06 14:19:54
【问题描述】:
我已尝试遵循此处的建议:https://www.baeldung.com/spring-inject-bean-into-unmanaged-objects
只是发现它正在编译但实际上并没有做它应该做的事情。未在非托管对象中设置自动装配的 bean。
@SpringBootApplication
@EnableSpringConfigured
public class SpringApp {
...
public class ApiClient {
private static String result = "not set";
//this would be called from another applicaiton written in a different language potentially.
public String apiInterface(String message) {
//This is where we're going to have to create Spring, where the languages 'join'.
SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringApp.class);
builder.run();
System.out.println("Running legacy code...");
LegacyCode oldCode = new LegacyCode();
result = oldCode.doLegacyStuff("hello world");
return result;
}
}
...
@Configurable(preConstruction = true)
public class LegacyCode {
@Autowired
MessageSender sender; //let's pretend we Spring-fied this bit of code but not the Legacy code that uses it.
public String doLegacyStuff(String message) {
sender.send(message);
sender.close();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
return "interupted";
}
return "ok";
}
}
这就是代码的要点。完整代码在github这里:https://github.com/AlexMakesSoftware/SpringConsoleApp3
我得到的输出是:
Exception in thread "main" java.lang.NullPointerException
at demo.LegacyCode.doLegacyStuff(LegacyCode.java:13)
at demo.ApiClient.apiInterface(ApiClient.java:17)
at demo.DummyApplication.main(DummyApplication.java:7)
这只能意味着@Autowired MessageSender 没有被注入。
任何想法我做错了什么?
编辑:我应该指出,这是一个将 Spring 缓慢集成到遗留代码库中的更复杂项目的简单示例。我不能简单地“让它全部成为 Spring”,也不能转移 Spring 的初始化位置,因为这个遗留代码是从另一个用另一种语言编写但在 JVM 中运行的应用程序(尽管是一个更简单的应用程序)调用的。是的,这很可怕,我知道。
【问题讨论】:
标签: java spring spring-boot aspectj