java spring使用@Autowired與構造器進行變量初始化

如果要在構造器裏引用其他被依賴的bean來初始化類的變量,較好的實現方式是

  1. 用@Autowired註解構造函數
  2. 並且增加一個有依賴關係的傳參
  3. 同時類變量也用@Autowired註解以便其它函數使用(不必在構造函數裏使用this.client = client;這種方式來手動賦值)。
@Service
public class StoreService {
	@Autowired
	private Client client;

        private final Store store;

	@Autowired
	public StoreService(Client client) {
	    this.store = client.getStore();
	}

        public void doLogic(){
             this.client.print();
             this.store.print();
        }
}

還有一種方式是另外寫一個初始化函數並用@PostConstruct註解,但這種方式有個缺點是不能初始化final的類變量。

@Service
public class StoreService {
	@Autowired
	private Client client;

        private Store store;


        public StoreService() {

	}

	@PostConstruct
	private void init() {
             this.store = client.getStore();
	}


        public void doLogic(){
             this.client.print();
             this.store.print();
        }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章