Java资源超类注入的对象为空。

huangapple go评论46阅读模式
英文:

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(&quot;index&quot;)
@Api(tags={&quot;IndexResource&quot;})
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(&quot;mytrips&quot;)
@ApiOperation(value=&quot;Returns the list of &#39;My Trips&#39; trips. If person who logged in is a travel agent, then get all trips belonging to them.&quot;)
@ApiResponses({
@ApiResponse(code=200, message=&quot;Success&quot;),
@ApiResponse(code=404, message=&quot;Not Found&quot;)
})
@Produces({ MediaType.APPLICATION_JSON })
public Response getMyTrips(@HeaderParam(&quot;Authorization&quot;) String token, @Context HttpServletRequest request)  {
TripSummaryResponse tripSummaryResponse = new TripSummaryResponse();
try {
AgentDTO agentDTO = getAgentDTO(token, request);
tripSummaryResponse.setAgentDTO(agentDTO);
Set&lt;TripSummaryDTO&gt; myTrips = new HashSet&lt;TripSummaryDTO&gt;();
List&lt;TripSummaryDTO&gt; requesterTripsInbox = tripService.findTripsForMemberDashboard(agentDTO.getMemberId());
List&lt;TripSummaryDTO&gt; agentTrips = tripService.findTripsForAgent(agentDTO.getMemberId(), Long.parseLong(agentDTO.getAgentObject().getAgentID()));
myTrips.addAll(requesterTripsInbox);
myTrips.addAll(agentTrips);
tripSummaryResponse.setTrips(myTrips);
tripSummaryResponse.setStatus(&quot;success&quot;);
return Response.ok().entity(tripSummaryResponse).build();
} catch (Exception e) {
logger.severe(e.getMessage());
tripSummaryResponse.setStatus(&quot;fail&quot;);
tripSummaryResponse.getMessages().add(new UIMessages(UIMessages.MessageType.ERROR, e.toString()+&quot;: &quot;+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(&quot;travelagentobject&quot;);
if (agentObject == null || !agentObject.getMemberID().equals(Long.toString(member.getId()))) {
agentObject = travelAgencyFacade.getAgentDetails(member.getId());
request.getSession().setAttribute(&quot;travelagentobject&quot;, agentObject);
}
agentDTO.setAgentObject(agentObject);
agentDTO.setMemberId(member.getId());
agentDTO.setUserName(userName);
} catch (Exception e) {
throw new Exception(&quot;Error trying to get the agent from the jwt token. &quot;+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(...); }
}

huangapple
  • 本文由 发表于 2020年8月24日 17:00:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63557807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定