我正在看这个例子:Building Applications in JavaFX 2.0他们显示了一个自定义的 SpringFxmlLoader:
import java.io.IOException;
import java.io.InputStream;
import javafx.fxml.FXMLLoader;
import org.springframework.context.ApplicationContext;
public class SpringFxmlLoader
{
private ApplicationContext context;
public SpringFxmlLoader(ApplicationContext context)
{
this.context = context;
}
public Object load(String url, Class<?> controllerClass) throws IOException
{
InputStream fxmlStream = null;
try
{
fxmlStream = controllerClass.getResourceAsStream(url);
Object instance = context.getBean(controllerClass);
FXMLLoader loader = new FXMLLoader();
loader.getNamespace().put("controller", instance);
return loader.load(fxmlStream);
}
finally
{
if (fxmlStream != null)
{
fxmlStream.close();
}
}
}
}`
为什么需要创建一个特定的 Spring FXML 加载器?我的意思是,即使使用简单的 fxml 加载器,当您像这样加载 fxml 时:
AnchorPane page = (AnchorPane) FXMLLoader.load(TabePaneGraph.class.getResource("Sample.fxml"));
无论如何都会调用示例 Controller ,并且仍然会完成任何初始化。我试图理解这个特定的自定义 SpringFxmlLoader 实现背后的动机。
最佳答案
给猫剥皮的方法有很多种。我猜测在那篇文章中使用 spring 的动机是因为许多 Web 开发人员都熟悉它。它还可能使它看起来更像是 Java EE 应用程序的替代品。确实如此,但不是因为你可以使用 spring 。
您不需要任何依赖注入(inject)框架来使用 JavaFX 进行开发,事实上,我们需要仔细查看我们的依赖项,因为如果您希望用户下载您的应用程序,它们会增加下载时间。
关于spring - 为什么需要特定的 Spring FXML 加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13838213/