Java - Spring 自动连线分配空值



我正在尝试将 spring xml 配置(仅用于自动连接某些对象 - 业务逻辑类和 jdbcTemplate)与 javafx 一起使用,但每当我使用 @Autowired 对象都会变为空。

这是我的主类代码:

@Component
public class App extends Application {
    public static ApplicationContext appContext;
    public static Stage window;
    static {
        appContext = new ClassPathXmlApplicationContext("spring//beans.xml");
    }
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage primaryStage) throws Exception {
        System.out.println("test1");
        window = primaryStage;
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("scenes/Login.fxml"));
        Scene scene = new Scene(root);
        primaryStage.setTitle(Titles.APPLICATION_TITLE);
        primaryStage.setScene(scene);
        primaryStage.show();
        window.setOnCloseRequest(e -> closeProgram(e));
        System.out.println("test2");
    }
    private void closeProgram(WindowEvent windowEvent) {
        try {
            windowEvent.consume();
            CommonUtility.openNewWindow("ConfirmExit", Titles.APPLICATION_TITLE);
        } catch (IOException e) {
            e.printStackTrace();
        }
}
}

Spring 配置文件,豆.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <context:annotation-config />
    <context:component-scan base-package="in.csitec.sp" />
    <import resource="classpath:database-config1.xml" />
    <bean id="taskExecutor"
        class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="queueCapacity" value="25" />
        <property name="WaitForTasksToCompleteOnShutdown" value="true" />
    </bean>

</beans>

登录控制器 :

@Component
public class LoginController implements Initializable {

    @FXML
    private Label statusLabel;
    @FXML
    private TextField usernameTextField, passwordTextField;
    @FXML
    private Button loginButton;
    @FXML
    private ProgressBar progressBar;
    private Task<Object> loginTask;
    public static String loggedInUser;
    @Autowired
    LoginManager loginManager;
    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
    public void onLoginButtonClick(ActionEvent actionEvent){
        if (usernameTextField.getText().isEmpty()) {
            statusLabel.setText(Messages.EMPTY_USERNAME);
            NotificationManager.showNotification(Titles.APPLICATION_TITLE, Messages.EMPTY_USERNAME);
            return;
        }
        if (passwordTextField.getText().isEmpty()) {
            statusLabel.setText(Messages.EMPTY_PASSWORD);
            NotificationManager.showNotification(Titles.APPLICATION_TITLE, Messages.EMPTY_PASSWORD);
            return;
        }
        loginButton.setDisable(true);
        progressBar.setProgress(0);
        loginTask = createLoginTask();
        progressBar.progressProperty().unbind();
        progressBar.progressProperty().bind(loginTask.progressProperty());

        loginTask.messageProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if(LoginManager.statusCode.equalsIgnoreCase("1")){
                    System.out.println("Invalid username or password.");
                    progressBar.progressProperty().unbind();
                    loginButton.setDisable(false);
                    return;
                }
                System.out.println("Logged in successfully");
                progressBar.progressProperty().unbind();
                loginButton.setDisable(false);
            }
        });
        new Thread(loginTask).start();
    }
    private Task<Object> createLoginTask() {
        return new Task<Object>() {
            @Override
            protected Object call() throws Exception {
                try{
                    Map<String, String> requestMap = new HashMap<>();
                    requestMap.put(Constants.USERNAME, usernameTextField.getText());
                    requestMap.put(Constants.PASSWORD, passwordTextField.getText());
                    loginManager.loginManager(requestMap);
                    updateProgress(100, 100);
                    updateMessage("Got Response");
                }catch(Exception e){
                    System.out.println("checkin");
                    e.printStackTrace();                
                }
                return true;
            }
        };
    }
    public void onFooterHyperLinkClick(ActionEvent actionEvent) throws IOException, URISyntaxException {
        Desktop.getDesktop().browse(new URI(Hyperlinks.CSITEC_WEBSITE));
    }
}

在 LoginController 中,我有自动连线的 LoginManager 的对象,但它每次都被分配为 null,因此每当我调用 loginManager.loginManager(requestMap) 时,我不知道为什么会发生这种情况,因为我确定我的 bean.xml 文件正在加载,在该文件中,我已经编写了从基本包扫描组件的配置,并且我还在我的 LoginManager 类文件中写入了@Component。

这也是LoginManager的代码:

@Component
public class LoginManager {
    @Autowired
    CommonDAO commonDAO;
    @Autowired
    JdbcTemplate jdbcTemplate1;
    public static String statusCode;
    public static String errorMessage;

    public void loginManager(Map<String, String> requestMap){
        try{
            String userName = requestMap.get(Constants.USERNAME);
            String passwordSHA = requestMap.get(Constants.PASSWORD);
            final byte[] authBytes = passwordSHA.getBytes(StandardCharsets.UTF_8);
            final String encodedPassword = Base64.getEncoder().encodeToString(authBytes);
            Object[] params = { userName, encodedPassword };
            String sqlQuery = ResourceFileReader.getSQLQuery(LookupSQLQueries.AUTHENTICATE_USER_QUERY);
            boolean result = commonDAO.validate(sqlQuery, params, jdbcTemplate1);
            if (!result) {
                errorMessage = Messages.INVALID_USERNAME_OR_PASSWORD;
                statusCode = "1";
                return;
            }
            statusCode = "0";
        }catch(Exception e){
            errorMessage = Messages.SOMETHING_WENT_WRONG;
            statusCode = "1";
        }
    }

}

请帮助我并指导我使其工作。

我不是JavaFX的专家,但似乎你的对象是由JavaXF而不是Spring管理的,因此没有发生自动连接。

你需要告诉JavaXF如何处理Spring。请参阅 JavaFX 和 Spring - bean 不会自动连线:

public class SpringFxmlLoader {
    private static final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringApplicationConfig.class);
    public Object load(String url, String resources) {
        FXMLLoader loader = new FXMLLoader();
        loader.setControllerFactory(clazz -> applicationContext.getBean(clazz));
        loader.setLocation(getClass().getResource(url));
        loader.setResources(ResourceBundle.getBundle(resources));
        try {
            return loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

正在loader.setControllerFactory(clazz -> applicationContext.getBean(clazz));的重要线路

教程

  • 上面的链接提到了本教程。
  • 你也可以检查这个;

最新更新