Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-Spring自动连线赋值null_Java_Xml_Spring_Javafx - Fatal编程技术网

Java-Spring自动连线赋值null

Java-Spring自动连线赋值null,java,xml,spring,javafx,Java,Xml,Spring,Javafx,我试图用javafx使用SpringXML配置(仅用于自动连接某些对象-业务逻辑类和jdbcTemplate),但每当我使用@Autowired时,对象就会变为null 这是我的主类代码: @Component public class App extends Application { public static ApplicationContext appContext; public static Stage window; static { a

我试图用javafx使用SpringXML配置(仅用于自动连接某些对象-业务逻辑类和jdbcTemplate),但每当我使用@Autowired时,对象就会变为null

这是我的主类代码:

@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配置文件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>

登录控制器:

@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实现可初始化{
@FXML
自有品牌;
@FXML
私有TextField用户名TextField、密码TextField;
@FXML
私人按钮登录按钮;
@FXML
私人ProgressBar ProgressBar;
专用任务登录任务;
公共静态字符串loggedInUser;
@自动连线
LoginManager LoginManager;
@凌驾
公共void初始化(URL位置、ResourceBundle资源){
}
public void onLoginButtonClick(ActionEvent ActionEvent){
if(usernameTextField.getText().isEmpty()){
statusLabel.setText(Messages.EMPTY_USERNAME);
NotificationManager.showNotification(Titles.APPLICATION\u TITLE,Messages.EMPTY\u USERNAME);
返回;
}
if(passwordTextField.getText().isEmpty()){
statusLabel.setText(Messages.EMPTY_PASSWORD);
NotificationManager.showNotification(Titles.APPLICATION\u TITLE,Messages.EMPTY\u PASSWORD);
返回;
}
loginButton.setDisable(true);
progressBar.setProgress(0);
loginTask=createLoginTask();
progressBar.progressProperty().unbind();
progressBar.progressProperty().bind(loginTask.progressProperty());
loginTask.messageProperty().addListener(新的ChangeListener(){
@凌驾

public void changed(observevalue我不是JavaFX方面的专家,但您的对象似乎是由JavaXF而不是Spring管理的,因此没有发生自动连接

您需要告诉JavaXF如何处理Spring。请参阅:

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

教程
  • 上面的链接提到
  • 你可以检查

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

您需要告诉JavaXF如何处理Spring。请参阅:

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

教程
  • 上面的链接提到
  • 你可以检查

您是否在CommonDAO上添加了spring注释?您只能注入定义为spring bean的bean。为什么要在控制器中注入jdbcTemplate?您不认为,DAO层应该具有这种依赖关系,而不是控制器层。关于null…请通读这篇文章@AmitBhati I have@Component在CommonDA中O同样,这里的主要问题是LoginManager没有自动连接。我已经评论了@autowired CommonDAO CommonDAO和@autowired JdbcTemplate jdbcTemplate1,但LoginManager仍然没有自动连接。应用程序的结构无法正常工作。JavaFX应用程序中的
应用程序
子类是条目p应用程序的点:将
application
中的
start()
方法(或
init()
方法)视为传统Java应用程序中
main()
的替代方法。JavaFX框架在启动时创建
应用程序
类的实例,并调用
init()
,然后
启动()
。因此,没有办法让spring管理
应用程序
实例:当您创建应用程序上下文时,
应用程序
实例已经创建。您是否在CommonDAO上添加了spring注释?您只能注入定义为spring bean的bean。为什么要在co中注入jdbcTemplatecontroller?你不认为,DAO层应该有这个依赖关系而不是控制器层。关于null…请通读这篇文章@AmitBhati我也在那个CommonDAO中写了@Component,这里主要的是LoginManager没有自动连接,我已经评论了@autowired CommonDAO CommonDAO和@autowired JdbcTemplate jdbcTemplate1但LoginManager仍然没有自动连接。应用程序的结构无法正常工作。JavaFX应用程序中的
应用程序
子类是应用程序的入口点:想想
start()
方法(或
init()
方法)在
应用程序中
替换传统Java应用程序中的
main()
。JavaFX框架在启动时创建
应用程序
类的实例,并调用
init()
,然后
start()
。因此,没有办法让spring管理
应用程序
实例:当您创建应用程序上下文时,
应用程序
实例已经创建。我看到了这个示例,您的理论可能是正确的,但我找不到任何理由。有没有办法用spring xml configu实现它定量(非java配置)@SiddharthSachdeva与XML配置完全相同:这与如何配置Spring无关。只需使用
ClassPathXmlApplicationContext
初始化
applicationContext即可。我看到了这个示例,您的理论可能是正确的,但我找不到任何理由。有没有办法使用spring xml配置(而不是java配置)@siddharthachdeva与xml配置完全相同:这与如何配置spring无关。只需使用
ClassPathXmlApplicationContext
初始化
applicationContext
@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";
        }
    }


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