英文:
Java Resource superclass injected objects are null
问题
我正在使用Java 1.7和`javax.inject.Inject`。
当我只有一个类(即没有向超类抽象功能),它可以正常工作。然而,当我创建一个超类时,超类中注入的成员变量为`null`。
例如,下面是不为null的:
TripServiceLocal tripService;
但是这些是null的:
@Inject
JwtTokenUtil jwtTokenUtil;
@Inject
MemberServiceLocal memberService;
@Inject
private TravelAgencyFacadeLocal travelAgencyFacade;
**问题**
为什么超类中注入的成员变量为null?如何解决这个问题?
我有以下的REST资源:
**IndexResource.java**
@Path("index")
@Api(tags={"IndexResource"})
public class IndexResource extends BaseResource {
private static final Logger logger = Logger.getLogger(IndexResource.class.getName());
@Inject
TripServiceLocal tripService;
/**
* 我的旅行作为旅行代理
*/
@GET
@Path("mytrips")
@ApiOperation(value="返回'我的旅行'旅行列表。如果登录的人是旅行代理,则获取属于他们的所有旅行。")
@ApiResponses({
@ApiResponse(code=200, message="成功"),
@ApiResponse(code=404, message="未找到")
})
@Produces({ MediaType.APPLICATION_JSON })
public Response getMyTrips(@HeaderParam("Authorization") String token, @Context HttpServletRequest request) {
TripSummaryResponse tripSummaryResponse = new TripSummaryResponse();
try {
AgentDTO agentDTO = getAgentDTO(token, request);
tripSummaryResponse.setAgentDTO(agentDTO);
Set<TripSummaryDTO> myTrips = new HashSet<TripSummaryDTO>();
List<TripSummaryDTO> requesterTripsInbox = tripService.findTripsForMemberDashboard(agentDTO.getMemberId());
List<TripSummaryDTO> agentTrips = tripService.findTripsForAgent(agentDTO.getMemberId(), Long.parseLong(agentDTO.getAgentObject().getAgentID()));
myTrips.addAll(requesterTripsInbox);
myTrips.addAll(agentTrips);
tripSummaryResponse.setTrips(myTrips);
tripSummaryResponse.setStatus("success");
return Response.ok().entity(tripSummaryResponse).build();
} catch (Exception e) {
logger.severe(e.getMessage());
tripSummaryResponse.setStatus("fail");
tripSummaryResponse.getMessages().add(new UIMessages(UIMessages.MessageType.ERROR, e.toString()+": "+e.getLocalizedMessage()));
return Response.status(Response.Status.BAD_REQUEST).entity(tripSummaryResponse).build();
}
}
}
**BaseResource.java**
public class BaseResource {
@Inject
JwtTokenUtil jwtTokenUtil;
@Inject
MemberServiceLocal memberService;
@Inject
private TravelAgencyFacadeLocal travelAgencyFacade;
/**
* 从jwt中获取代理
*
* @param jwtToken
* @return
* @throws Exception
*/
protected AgentDTO getAgentDTO(String jwtToken, HttpServletRequest request) throws Exception {
AgentDTO agentDTO = new AgentDTO();
try {
String token = jwtTokenUtil.getJwtToken(jwtToken);
String userName = jwtTokenUtil.extractUserName(token);
Member member = memberService.getMemberByUserName(userName);
AgentObject agentObject = (AgentObject)request.getSession().getAttribute("travelagentobject");
if (agentObject == null || !agentObject.getMemberID().equals(Long.toString(member.getId()))) {
agentObject = travelAgencyFacade.getAgentDetails(member.getId());
request.getSession().setAttribute("travelagentobject", agentObject);
}
agentDTO.setAgentObject(agentObject);
agentDTO.setMemberId(member.getId());
agentDTO.setUserName(userName);
} catch (Exception e) {
throw new Exception("尝试从jwt令牌获取代理时出错。 "+e.getLocalizedMessage(), e);
}
return agentDTO;
}
}
英文:
I am using Java 1.7. and javax.inject.Inject
.
When I have just one class (i.e. no abstracted functionality to the superclass), it works perfectly. However, when I create a superclass, then the superclasses injected member variables are null
.
For example, below.
the following is not null:
TripServiceLocal tripService;
But these are null:
@Inject
JwtTokenUtil jwtTokenUtil;
@Inject
MemberServiceLocal memberService;
@Inject
private TravelAgencyFacadeLocal travelAgencyFacade;
Question
Why are the super classes injected member variables null? How do I solve this?
I have the following REST resource:
IndexResource.java
@Path("index")
@Api(tags={"IndexResource"})
public class IndexResource extends BaseResource {
private static final Logger logger = Logger.getLogger(IndexResource.class.getName());
@Inject
TripServiceLocal tripService;
/**
* My Trips as travel agent
*/
@GET
@Path("mytrips")
@ApiOperation(value="Returns the list of 'My Trips' trips. If person who logged in is a travel agent, then get all trips belonging to them.")
@ApiResponses({
@ApiResponse(code=200, message="Success"),
@ApiResponse(code=404, message="Not Found")
})
@Produces({ MediaType.APPLICATION_JSON })
public Response getMyTrips(@HeaderParam("Authorization") String token, @Context HttpServletRequest request) {
TripSummaryResponse tripSummaryResponse = new TripSummaryResponse();
try {
AgentDTO agentDTO = getAgentDTO(token, request);
tripSummaryResponse.setAgentDTO(agentDTO);
Set<TripSummaryDTO> myTrips = new HashSet<TripSummaryDTO>();
List<TripSummaryDTO> requesterTripsInbox = tripService.findTripsForMemberDashboard(agentDTO.getMemberId());
List<TripSummaryDTO> agentTrips = tripService.findTripsForAgent(agentDTO.getMemberId(), Long.parseLong(agentDTO.getAgentObject().getAgentID()));
myTrips.addAll(requesterTripsInbox);
myTrips.addAll(agentTrips);
tripSummaryResponse.setTrips(myTrips);
tripSummaryResponse.setStatus("success");
return Response.ok().entity(tripSummaryResponse).build();
} catch (Exception e) {
logger.severe(e.getMessage());
tripSummaryResponse.setStatus("fail");
tripSummaryResponse.getMessages().add(new UIMessages(UIMessages.MessageType.ERROR, e.toString()+": "+e.getLocalizedMessage()));
return Response.status(Response.Status.BAD_REQUEST).entity(tripSummaryResponse).build();
}
}
}
BaseResource.java
public class BaseResource {
@Inject
JwtTokenUtil jwtTokenUtil;
@Inject
MemberServiceLocal memberService;
@Inject
private TravelAgencyFacadeLocal travelAgencyFacade;
/**
* Gets an agent from a jwt
*
* @param jwtToken
* @return
* @throws Exception
*/
protected AgentDTO getAgentDTO(String jwtToken, HttpServletRequest request) throws Exception {
AgentDTO agentDTO = new AgentDTO();
try {
String token = jwtTokenUtil.getJwtToken(jwtToken);
String userName = jwtTokenUtil.extractUserName(token);
Member member = memberService.getMemberByUserName(userName);
AgentObject agentObject = (AgentObject)request.getSession().getAttribute("travelagentobject");
if (agentObject == null || !agentObject.getMemberID().equals(Long.toString(member.getId()))) {
agentObject = travelAgencyFacade.getAgentDetails(member.getId());
request.getSession().setAttribute("travelagentobject", agentObject);
}
agentDTO.setAgentObject(agentObject);
agentDTO.setMemberId(member.getId());
agentDTO.setUserName(userName);
} catch (Exception e) {
throw new Exception("Error trying to get the agent from the jwt token. "+e.getLocalizedMessage(), e);
}
return agentDTO;
}
}
答案1
得分: 1
以下是翻译好的内容:
有许多充分的理由不使用直接字段注入。如果您将这些字段声明为final并使用构造函数注入,那么仍然可以在子类构造函数中使用@Inject
。如果您和我一样不喜欢额外的样板代码,请参阅该链接以了解忍受它的原因。
public abstract class BaseResource {
private final JwtTokenUtil jwtTokenUtil;
private final MemberServiceLocal memberService;
private final TravelAgencyFacadeLocal travelAgencyFacade;
@Inject
protected BaseResource(
JwtTokenUtil jwtTokenUtil,
MemberServiceLocal memberService,
TravelAgencyFacadeLocal travelAgencyFacade) {...}
}
public class IndexResource extends BaseResource {
@Inject
public IndexResource(
JwtTokenUtil jwtTokenUtil,
MemberServiceLocal memberService,
TravelAgencyFacadeLocal travelAgencyFacade) { super(...); }
}
英文:
There are many good reasons to not use direct field injection. If you make these final and use constructor injection then you can still throw @Inject
at the subclass constructor. If, like me, you don't like the additional boilerplate, see that link for reasons to put up with it.
public abstract class BaseResource {
private final JwtTokenUtil jwtTokenUtil;
private final MemberServiceLocal memberService;
private final TravelAgencyFacadeLocal travelAgencyFacade;
@Inject
protected BaseResource(
JwtTokenUtil jwtTokenUtil,
MemberServiceLocal memberService,
TravelAgencyFacadeLocal travelAgencyFacade) {...}
}
public class IndexResource extends BaseResource {
@Inject
public IndexResource(
JwtTokenUtil jwtTokenUtil,
MemberServiceLocal memberService,
TravelAgencyFacadeLocal travelAgencyFacade) { super(...); }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论