我有带有springboot的JavaFX应用程序。问题是一个bean使用@PostConstruct创建了2次,并出现了有关已使用串行端口的异常。
Hovewer,我注意到我同时拥有@SpringBootApplication和@ComponentScan和@Configuration批注。我在根包中有SpringConfig类。
主类
package sample;
@SpringBootApplication
public class AppStart extends Application {
private Stage primaryStage;
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
Platform.setImplicitExit(false);
Parent root = FXMLLoader.load(getClass().getResource("/primal.fxml"));
primaryStage.setTitle("ИС СиАТВ АО ГНЦ НИИАР");
primaryStage.getIcons().add(new Image("/icon.png"));
primaryStage.setScene(new Scene(root, 1400, 900));
createTray();
primaryStage.show();
primaryStage.setOnCloseRequest(event -> {
primaryStage.hide();
});
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
SpringApplicationBuilder builder = new SpringApplicationBuilder(AppStart.class);
builder.headless(false);
ConfigurableApplicationContext context = builder.run(args);
launch(args);
}
SpringConfig
package sample;
@Configuration
@PropertySource({"classpath:com.properties", "classpath:application.properties"})
@ComponentScan
public class SpringConfig {
@Bean
public SerialPort serialPort(@Value("${serialPort.portName}") String portName){
return new SerialPort(portName);
}
@Bean
public AnnotationMBeanExporter annotationMBeanExporter(){
AnnotationMBeanExporter annotationMBeanExporter = new AnnotationMBeanExporter();
annotationMBeanExporter.addExcludedBean("dataSource");
return annotationMBeanExporter;
}
}
ComReader-此类创建了2次,并通过openPort()函数调用异常
package sample.Model
@Component
public class ComReader {
@Autowired
private EventListener eventListener;
@Autowired
public SerialPort serialPort;
@Value("${serialPort.baudRate}")
private int baudRate;
@Value("${serialPort.dataBits}")
private int dataBits;
@Value("${serialPort.stopBits}")
private int stopBits;
@Value("${serialPort.parity}")
private int parity;
@PostConstruct
public void init(){
try {
System.out.println("Opening port: " + serialPort.getPortName());
serialPort.openPort();
serialPort.setParams(baudRate,dataBits,stopBits,parity);
serialPort.addEventListener(eventListener, 1);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
源文件层次结构:
-sample (folder)
-Model (folder)
-ComReader.java
-Controller.java
-Repository (folder)
-CRUD interfaces
-AppStart.java
-SpringConfig.java
在这种情况下,我有工作程序,但仅收到“使用中的端口”异常。
如果我从主类中删除@SpringBootApplication批注,则会收到异常-没有类型为'sample.Repository.CallDetailRecordRepository的qyalifying bean期望至少有1个可以作为自动装配候选的bean。
如果删除@ComponentScan,则会收到异常-没有可用的'sample.Model.Controller'类型的合格Bean。在setContextFactory(ctx :: getBean);上
最佳答案
没关系!
我删除了
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);