title: Spring Boot - Tomcat JNDI fails in Service beans
body: <p>I'm trying to switch datasource from c3p0 to Tomcat JNDI in a Spring Boot 1.1.6 web project. I've found a sample application in <a href="https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi" rel="nofollow">GitHub</a>, which works fine when DataSource instance is accessed from <code>@RestController</code> annotated class. </p>
  
  <pre><code>@RestController
  public class TestController {
  
    @Autowired
    private DataSource dataSource;
  
    @RequestMapping("/test")
    @ResponseBody
    public String test() {
  
    // Gets object instance... everything is OK...
    System.out.println(this.dataSource); 
    }
  </code></pre>
  
  <p>However, when I try to inject same datasource to <code>@Service</code> annotated bean, I get <code>javax.naming.NameNotFoundException</code> as soon as instance is used in code.</p>
  
  <pre><code>@Service
  public class TestService {
  
    @Autowired
    private DataSource dataSource;
  
    @PostConstruct
    private void init() {
  
      // Throws exception...
      System.out.println(this.dataSource);
  
  }
  </code></pre>
  
  <p>Stack trace:</p>
  
  <pre><code>Caused by: javax.naming.NameNotFoundException: Name [java:comp/env/jdbc/myDataSource] is not bound in this Context. Unable to find [java:comp].
      at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
      at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
      at javax.naming.InitialContext.lookup(InitialContext.java:411)
      at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:155)
      at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
      at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
      at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:179)
      at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
      at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:106)
      at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:135)
      ... 11 more
  </code></pre>
  
  <p>I wonder why JNDI datasource bean can not be accessed from @Service class ? Any ideas ?</p>