Getting null pointer exception @Resource annotation in tomcat 7

醉酒当歌 提交于 2019-12-05 16:07:23

Tomcat itself does not support @Resource injection. In other words, the servlet container does not recognize that annotation and can't do anything with it. Manual lookup works, because the resource is defined properly.

You need some dependency-injection framework:

  • spring
  • CDI (part of the JavaEE6 web-profile)
  • EJB (part of the JavaEE6 web-profile, not exactly a "DI framework")

Note Tomcat does support @Resource injection. You were really really close.

The issue was you used:

  • @Resource(mappedName = "jdbc/myoracle")

This would have worked:

  • @Resource(name = "jdbc/myoracle")

I'll note that had you been using Apache TomEE (the JavaEE certified version of Tomcat), both would have worked with no changes to your context.xml

Plus you get CDI, EJB, JPA and other things mentioned in some of the other answers.

Small comparison here.

There are a lot of things going on here. First off, you don't need a resource-ref in your web.xml unless you're going to let the application server manage the data source. This is useful if you use something like IBM WAS, or Apache Tomcat, and specify the data source parameters in your server config. If you do this, you'll want to keep the resource ref, and add a jndi factory bean:

<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
     <property name="jndiName"><value>java:comp/env/jdbc/myOracle</value></property>
</bean>

Coincidentally, I'm pretty sure your set up will work now if you simply add this bean.

From what you have now, or if you use a jndi factory bean, all you have to do is autowire the bean from there:

@Autowired
@Qualifier("myDataSource")
DataSource dataSource;

If you would like to verify the state of your bean, you could always implement InitializingBean which will force you to implement afterPropertiesSet

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(dataSource);
}

Although 1@Autowired` should through an exception if it can't autowire by default.

It's also worth noting that it's a better paradigm to use a constructor:

@Autowired
public MyClass(@Qualifier("myDataSource") DataSource dataSource) {
   this.dataSource = dataSource;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!