Issue
Orignially I have a simple spring boot project, with a config file called DemoConfig.java, shown as below:
@Configuration
@PropertySource("classpath:application.properties")
public class DemoConfig
{
@Value("${deviceName}")
private String deviceName;
@Value("${platformName}")
private String platformName;
@Value("${platformVersion}")
private String platformVersion;
@Value("${appPackage}")
private String appPackage;
@Value("${appActivity}")
private String appActivity;
Now I want to apply javafx onto my project, somehow start a configuration page for users to configure these values. So I have this DemoController.java to serve as the fx:controller.
@Component
public class DemoController
{
@Resource
private DemoConfig demoConfig;
public TextField platformName = new TextField(demoConfig.getPlatformName());
public TextField platformVersion = new TextField(demoConfig.getPlatformVersion());
public TextField deviceName = new TextField(demoConfig.getDeviceName());
public TextField appActivity = new TextField(demoConfig.getAppActivity());
public TextField appPackage = new TextField(demoConfig.getAppPackage());
}
Now I end up with : The initialization of DemoController will fail because DemoConfig hasn't been injected as a bean yet, I am kinda confused as to how to combine the Controller with my Configuration class. My goal is simple, just to initialize the Controller's textfield with the values of bean DemoConfig. Any ideas would help! Thanks!
Solution
EDIT: I did not take FXML into account for my answer. All credits go to James_D for valid comment after answer was already accepted.
When using FXML (Prefered)
From the comments:
If this is the controller for an FXML file, you should not be instantiating the text fields at all. If they are declared in the FXML file, the FXMLLoader will instantiate them and inject them into the controller. Just set the text in the controller’s initialize() method; your dependencies will have been injected when that is called. – James_D
Not taking into account FXML
Use @PostConstruct: https://www.baeldung.com/spring-postconstruct-predestroy This should insure your bean is injected (if there are no other issues).
Place all your textfield initializations in the postconstruct:
@Component
public class DemoController
{
@Autowire
private DemoConfig demoConfig;
public TextField platformName;
public TextField platformVersion;
public TextField deviceName;
public TextField appActivity;
public TextField appPackage;
@PostConstruct
private void postConstruct() {
platformName = new TextField(demoConfig.getPlatformName());
platformVersion = new TextField(demoConfig.getPlatformVersion());
deviceName = new TextField(demoConfig.getDeviceName());
appActivity = new TextField(demoConfig.getAppActivity());
appPackage = new TextField(demoConfig.getAppPackage());
}
}
Answered By - Tom Cools