0
我想從用戶地址中的區號獲取公交/公交車站信息打開api。如何根據用戶地區代碼注入服務類
區域是城市,城市提供彼此不同的巴士信息api。
TrafficController.java
@Controller
public class TrafficController {
....
@Autowired
public UserService userService;
public TrafficService trafficService;
....
@RequestMapping(value="/api/traffic/stations")
public List<....> getNearStations(HttpServerletRequest req) {
String userId = SessionAttrs.getUserId(req.getSession());
User user = userSerivce.getUser(userId);
trafficService = (TrafficService) Class.forName("com.myservice.service.impl.TrafficService_"+user.house.apt.address.area_code + "_Impl").newInstence();
return trafficService.getStations(user.house.apt.latitude, user.house.apt.longitude, 300, 2);
}
}
TrafficService_11_Impl.java
@Service
public Class TrafficService_11_Impl implemnet TrafficService {
@Autowired
TrafficRepository trafficRepository;
@Override
public List<Station> getStations(double lat, double lng, int ratius, int retryCount) {
final String cacheKey = "getStations " + lat + " " + lng + " " + radius;
TrafficeCache cache = trafficRepository.fineOne(chcheKey); // run time NullPointerException, trafficRepository is null
if (null == cache) {
...
get area code 11 api call logic
...
}
...
return ...;
}
}
TrafficRepository.java
public interface TrafficRepository extends JpaRepository<TrafficCache, String> {
}
該代碼發生運行時的NullPointerException在
TrafficService_11_Impl.java在
TrafficeCache緩存= trafficRepository.fineOne(chcheKey);
運行時NullPointerException異常,trafficRepository爲null
Otherly在TrafficController.java
@Autowired
public TrafficService trafficService
拖放代碼
trafficService = (TrafficService) Class.forName("com.myservice.service.impl.TrafficService_"+user.house.apt.address.area_code + "_Impl").newInstence();
是正確的結果
如何在String引導中根據用戶區號注入服務類?
縮進代碼,添加更好的格式。問題仍然很少問 –
您是否打算爲*每個可能的區號創建一個單獨的'TrafficService'實現?無論你的「區號」是什麼,以及可能有多少,這都不是你應該怎麼做的。創建一個封裝區域代碼之間差異的'TrafficService'實現。 – kryger
[爲什麼我的Spring @Autowired字段爲空]?(http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – chrylis