Skip to main content

@Resource Dependency Injection: Resource won't inject

4 replies [Last post]
Joined: 2005-04-17

I am trying to get a DataSource injected into my bean.
I have clientDataSource defined with a resource-ref in my sun-web.xml file, but clientDataSource is not being populated in instances of this bean.

How do I make this injection happen?

<br />
public class TokenHandlerBean {</p>
<p>    private final static String salt = "Some secret";<br />
    @Resource<br />
    private DataSource clientDataSource;<br />
    private Map tokenMap;</p>
<p>    @PostConstruct<br />
    public void initialize() {<br />
        try {<br />
            Map tempTokenMap = new HashMap();<br />
            final Connection connection = clientDataSource.getConnection();<br />
            PreparedStatement stmt = connection.prepareStatement("SELECT DISTINCT clientName FROM client_table");<br />
            ResultSet rs = stmt.executeQuery();<br />
            while ( {<br />
                String clientName = rs.getString(1);<br />
                tempTokenMap.put(TokenGenerator.generate(clientName, salt), clientName);<br />
            }<br />
            tokenMap = tempTokenMap;<br />
            connection.close();<br />
        } catch (SQLException ex) {<br />
            throw new IllegalStateException(ex);<br />
        }<br />
<p>    public boolean isValid(String token) {<br />
        return getClientName(token) != null;<br />
<p>    public boolean isValid(String token, boolean reinit) {<br />
        return getClientName(token, reinit) != null;<br />
<p>    public String getClientName(String token) {<br />
        return getClientName(token, false);<br />
<p>    public Map  getTokenMap() {<br />
        return tokenMap;<br />
<p>    public String getClientName(String token, boolean reinit) {<br />
        String clientName = tokenMap.get(token);<br />
        if (clientName == null && reinit) {<br />
            initialize();<br />
            clientName = tokenMap.get(token);<br />
        }<br />
        return clientName;<br />
<p>    @PreDestroy<br />
    private void clear() {<br />
        tokenMap = null;<br />
<p>}<br />

I reference this bean in my jsp with:


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-03-29

Resource injection is not supported in ordinary JavaBeans class. However, JSF managed beans are supported.


Joined: 2005-04-17

Is there a way to do it without using JSF?

Joined: 2005-03-29

You can use the plain old web.xml + JNDI lookup. You declare a in web.xml, and look it up in your JavaBeans class. This is equivalent to @Resource injection.

You can also implement it in a servelt class, or a tag handler class where @Resource injections are supported.


Daniel Ortega Segura

You can also use Spring to manage your bean and let the framework inject the
DataSource for you.