Page 1 of 1

About Question enthuware.jwpv6.2.670 :

Posted: Thu Feb 16, 2012 9:05 am
by paf
Consider the following servlet code:

@WebServlet("/wftestservlet1")
public class WFTestServlet1 extends HttpServlet{

@Resource
private DataSource myDS;

//Other valid methods
...
}

Which of the following methods can access the DataSource myDS injected into the servlet by the container?
1. A method annotated with @Init
2. A method annotated with @PostConstruct
3. A method annotated with @Resource
4. The servlet's init() method.
5. In the servlet's constructor.

Explanation:
Note that resources are be injected prior to any lifecycle methods being called and the component instance being made available the application. This means, the injected resource will be available in the init() method and the @PostConstruct method (along with other methods such as service() or doXXX(), or even @PreDestroy method).

It cannot be available in the constructor because before the container can access the field to set the reference, the object needs to be constructed.
If this statement is true:
This means, the injected resource will be available in the init() method and the @PostConstruct method (along with other methods such as service() or doXXX(), or even @PreDestroy method).

then "A method annotated with @Resource" also can have access to the myDS, cannot it?

Re: About Question enthuware.jwpv6.2.670 :

Posted: Thu Feb 16, 2012 8:10 pm
by admin
Yes, it should be valid.
This has now been fixed. Thank you for your feedback!