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