我們的項目使用彈簧DI/IoC,所以我使用自動裝配來注入豆類。該程序需要在實例化過程中將參數傳遞給對象。參數在運行時已知(不在編譯時)。如何在使用彈簧自動佈線時傳遞構造函數參數?
如何在使用自動裝配時實現此目的。示例代碼如下。
接口 - 即時聊天
package com.example.demo.services;
public interface IMessage {
String message(String name);
}
實現 -
SayHelloService
package com.example.demo.services;
import org.springframework.stereotype.Service;
@Service
public class SayHelloService implements IMessage {
String id;
public SayHelloService(String id) {
super();
this.id = id;
}
@Override
public String message(String name) {
return "Hello Dear User - " + name + ". Greeter Id: " + id ;
}
}
MasterService
package com.example.demo.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class MasterService implements IMessage {
String creationTime;
MasterService() {
System.out.println("ms... default constructor");
creationTime = Long.toString(System.currentTimeMillis());
}
//classic java way of creating service
IMessage sayHelloServiceClassicWay = new SayHelloService(creationTime);
//how to achieve above using spring auto wiring. Below code does not exactly do same.
@Autowired
@Qualifier("sayHelloService")
IMessage sayHelloServiceAutoWired;
@Override
public String message(String name) {
return name.toString();
}
}
現在,在上述程序(在MasterService)如何更換
即時聊天sayHelloServiceClassicWay =新SayHelloService(創建時間);
帶有彈簧等效代碼。
爲變量創建一個getter和setter,然後在autowired字段上使用setter方法。 – user641887
在您的配置xml中,將SayHelloService的bean中的「creationTime」屬性指定爲constructor-arg。 Spring將自動裝入它。 – Coder
@ user641887,你可以添加一些代碼PLZ。 – samshers