亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 SQLiteDatabase 實例用作 Application 類中的靜態字段是個好主意嗎?

將 SQLiteDatabase 實例用作 Application 類中的靜態字段是個好主意嗎?

元芳怎么了 2023-06-14 11:15:52
Spring 只會在實例化 bean 之后或實例化時注入依賴項(取決于是否使用構造函數注入)。MyService但是,您現在在初始化 bean 之前發生的字段初始化期間訪問依賴項。因此,它無法MyService在字段初始化期間訪問,因為它尚未注入。您可以通過更改為routingKeys同時在構造函數中使用構造函數注入和初始化來簡單地修復它:@Configurationpublic class RabbitConfiguration {    private List<String> routingKeys ;    private MyService myService;    @Autowired    public RabbitConfiguration(MyService myService){        this.myService = myService        this.routingKeys = writeRoutingKeys();    }    private List<String> writeRoutingKeys() {        return myService.getRoutingKeys();     } }或者簡單地說:@Autowiredpublic RabbitConfiguration(MyService myService){    this.myService = myService    this.routingKeys = myService.getRoutingKeys();}我正在開發一個字典 android 應用程序。我在應用程序中使用數據庫來獲取單詞及其含義。SQLiteDatabase在課堂上使用靜態Application并在某些活動和課程中使用它是一種好方法嗎?public class App extends Application {  public static SQLiteDatabase database;  @Override  public void onCreate() {    super.onCreate();    database = SQLiteDatabase.openOrCreateDatabase(            Constants.MAIN_DB_PATH,            null);  }并以這種方式使用它:public class MainActivity extends AppCompatActivity {    ...    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        ...        Cursor cursor = App.database.rawQuery(query, null);        ...    }}和:public class MyClass{    ...    public MyClass() {        ...        Cursor cursor = App.database.rawQuery(query, null);        ...    }}
查看完整描述

1 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

由于您只需要此對象的一個實例,因此這是一種可行的方法。您可以定義數據庫:


public class Database{

    private static SQLiteDatabase localDatabase = null;

    private Database(){}


    public static SQLiteDatabase getLocalDatabase(){

        if (localDatabase == null){

            localDatabase = SQLiteDatabase.openOrCreateDatabase(...);

        }

        return localDatabase;

    }

}

在您的活動代碼中,您可以像這樣使用它:


Database.getLocalDatabase().rawQuery(...); 

編輯:要應用單例模式的所有規則,還要添加一個私有和空的構造函數,這樣您就不會意外地實例化對象。


查看完整回答
反對 回復 2023-06-14
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號