简体   繁体   English

Java-Spring Autowired分配null

[英]Java - Spring Autowired assigning null

I'm trying to to use spring xml configuration (only for autowiring some objects - business logic classes and jdbcTemplate) with javafx but whenever I'm using @Autowired the object is getting null. 我正在尝试通过javafx使用spring xml配置(仅用于自动装配某些对象-业务逻辑类和jdbcTemplate),但是每当我使用@Autowired时,对象就会为空。

Here's my code of Main class : 这是我的Main class代码:

@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 configuration file, beans.xml : 春季配置文件beans.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>

Login Controller : 登录控制器:

@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));
    }

}

Here in LoginController I have Autowired LoginManager's object but it is getting assigned null every time therefore whenever I'm calling loginManager.loginManager(requestMap), I have no clue why it is happening because I'm sure my beans.xml file is loading and in that file I have written configuration for component scanning from base package and I have also written @Component in my LoginManager class file. 在LoginController中,我已经自动连接了LoginManager的对象,但是每次都将其分配为null,因此,每当我调用loginManager.loginManager(requestMap)时,我都不知道为什么会发生这种情况,因为我确定我的bean.xml文件正在加载并在该文件中,我编写了用于从基本包进行组件扫描的配置,并且还在我的LoginManager类文件中编写了@Component。

Here's the code for LoginManager as well : 这也是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";
        }
    }


}

Please help me out and guide me to make it work. 请帮助我,并指导我使其工作。

I'm not expert on JavaFX, but it seems your object is managed by JavaXF rather than Spring, hence no autowiring is happening. 我不是JavaFX方面的专家,但是看来您的对象是由JavaXF而不是Spring管理的,因此没有自动装配发生。

You need to tell JavaXF how to deal with Spring. 您需要告诉JavaXF如何处理Spring。 See JavaFX and Spring - beans doesn't Autowire : 请参阅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; } } 

The important line being loader.setControllerFactory(clazz -> applicationContext.getBean(clazz)); 重要的一行是loader.setControllerFactory(clazz -> applicationContext.getBean(clazz));

Tutorials 讲解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM