簡體   English   中英

在 JavaFX + Spring Boot + Hibernate 應用程序中支持多種環境

[英]Support for multiple environments in JavaFX + Spring Boot + Hibernate application

我正在使用休眠在 Spring Boot 中構建 JavaFX 應用程序。 它連接到數據庫以顯示一些數據,目前它從屬性文件中獲取連接詳細信息,並使用純 Java 配置加載 sessionFactory、數據源和事務管理器 bean。 但是,我在多台遠程機器上有多個數據庫,每個數據庫都有不同的 IP 和用戶詳細信息。 理想情況下,我想顯示一個登錄表單,在應用程序啟動時提示輸入數據庫用戶名和密碼。 我不想從文件中讀取這些詳細信息。 有可能嗎? 我真的很感激這個問題的一些幫助。

編輯:設法實現這一點,在我的登錄控制器中,我只是實現了 ApplicationContextAware,然后使用文本字段中的數據手動加載注冊 bean。

您可以使用 Spring Boot Active Profile 功能

根據您當前的配置文件 PROD、DEV、PRE-PROD,您可以使用給定的 application.properties 文件激活某個配置。 您可以在此處找到完整的操作方法

編輯 2:

如果您想根據用戶輸入(例如它的憑據)更改整個配置,您必須動態更改屬性,並且似乎@RefreshScope完成這項工作。

壞消息是這個注解似乎只存在於Spring Cloud

這就是我的解決方案,唯一的缺點是我嘗試登錄失敗后無法登錄。 它工作正常,但如果我首先使用不正確的登錄憑據,然后使用正確的登錄憑據,則會引發異常,指出 EntityManagerFactory 已關閉。 (我確實刪除了 catch 塊中的 bean 定義,只是想讓代碼更短)

@Component
public class LoginController implements Initializable, ApplicationContextAware{

    @FXML
    private AnchorPane login;
    @FXML
    private JFXTextField dbUsernameTextField;
    @FXML
    private JFXPasswordField dbPasswordTextField;
    @FXML
    private JFXTextField boxUsernameTextField;
    @FXML
    private JFXPasswordField boxPasswordTextField;
    @FXML
    private JFXComboBox<ComboItem> environmentComboBox;
    @FXML
    private JFXButton loginButton;
    @Autowired 
    private Environment environment;

    @Autowired
    private OrderService orderService;

    private AnnotationConfigApplicationContext context;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        loginButton.setDisable(true);
        List<ComboItem> envs=new ArrayList<ComboItem>();
        String[]environments=environment.getProperty("environments").split(",");
        for(String s:environments) {
            environmentComboBox.getItems().add(new ComboItem(s.toUpperCase(),s));
        }
        environmentComboBox.setConverter(new StringConverter<ComboItem>() {
            @Override
            public String toString(ComboItem object) {
                return object.getKey();
            }
            @Override
            public ComboItem fromString(String string) {
                return null;
            }
        });
    }

    @FXML
    public void selectEnvironment() {
        if(!environmentComboBox.getSelectionModel().isEmpty())
            loginButton.setDisable(false);
    }

    @FXML
    public void authenticate(ActionEvent actionEvent) {

        String boxUsername=boxUsernameTextField.getText();
        String boxPassword=boxPasswordTextField.getText();
        try {
            context.registerBean("dataSource",DataSource.class,()->dataSource());
            context.registerBean("sessionFactory", LocalSessionFactoryBean.class,()->sessionFactory());     
            context.registerBean("transactionManager",HibernateTransactionManager.class,()->getTransactionManager());

            Order order=orderService.findById("");

            FXMLLoader fxmlLoader=new FXMLLoader(getClass().getResource("/fxml/Main.fxml"));
            fxmlLoader.setControllerFactory(context::getBean);
            Parent rootNode=fxmlLoader.load();
            Stage stage=(Stage) login.getScene().getWindow();
            Scene scene=new Scene(rootNode,400,300);
            stage.setScene(scene);
            stage.setTitle("Login");
            stage.setMaximized(true);
            stage.show();
            stage.setOnCloseRequest(event->JSchConnection.close());
        }catch(Exception e) {
        context.removeBeanDefinition("dataSource");
        context.removeBeanDefinition("sessionFactory");
        context.removeBeanDefinition("transactionManager");

            e.printStackTrace();
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=(AnnotationConfigApplicationContext) applicationContext;       
    }

    private  Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        properties.put("hibernate.show_sql", "false");
        properties.put("hibernate.format_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "none");
        return properties;
    }

    public  DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("myurl");
        dataSource.setUsername(dbUsernameTextField.getText());
        dataSource.setPassword(dbPasswordTextField.getText());
        return dataSource;
    }

    public  LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.mypackage" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(context.getBean(SessionFactory.class,"sessionFactory"));
        return transactionManager;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM