如何使用 Swing 应用程序配置 spring-boot [英] How to configure spring-boot with swing application
问题描述
我想使用 spring-boot-starter-data-jpa 功能来创建非 Web 应用程序.在 52.4 文档中说:
I'd like using spring-boot-starter-data-jpa features to create a non-web aplication. In the 52.4 documentation says:
您希望作为业务逻辑运行的应用程序代码可以是实现为 CommandLineRunner 并作为@Bean 定义.
Application code that you want to run as your business logic can be implemented as a CommandLineRunner and dropped into the context as a @Bean definition.
我的 AppPrincipalFrame 看起来像:
@Component
public class AppPrincipalFrame extends JFrame implements CommandLineRunner{
private JPanel contentPane;
@Override
public void run(String... arg0) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppPrincipalFrame frame = new AppPrincipalFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
和启动应用程序类看起来像:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
AppPrincipalFrame appFrame = context.getBean(AppPrincipalFrame.class);
}
}
但是不起作用.有人有这方面的样本吗?
But does not work. Anybody have a sample about this?
已编辑并添加了例外.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appPrincipalFrame'.
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [es.adama.swing.ui.AppPrincipalFrame]: Constructor threw exception; nested exception is java.awt.HeadlessException
问候.
推荐答案
你发布问题已经有一段时间了,但我在一个旧项目中遇到了同样的问题,我正在迁移并想出了不同的方法,我认为这更清楚,让事情发挥作用.
It's been a while since you posted the question, but I run out with the same problem in a old project that I'm migrating and figured a different way, I think that more clear, to make the things work.
代替使用 SpringApplication.run(Application.class, args);
你可以使用:new SpringApplicationBuilder(Main.class).headless(false).run(args);
并且没有必要让玩具应用程序类从 JFrame 扩展.因此,代码可能如下所示:
Instead of using SpringApplication.run(Application.class, args);
you can use: new SpringApplicationBuilder(Main.class).headless(false).run(args);
and it isn't necessary to make toy Application class extends from JFrame. Therefore the code could look like:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(Application.class).headless(false).run(args);
AppPrincipalFrame appFrame = context.getBean(AppPrincipalFrame.class);
}
这篇关于如何使用 Swing 应用程序配置 spring-boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!