初始化后,Spring 3.0注射为null

Roy*_*han 0 spring ioc-container spring-3

我试图将数据源对象注入servlet.我有使用set方法打印的记录器.它适用于pre-inialization.但是当我请求servlet时,它给了我nullPointerException.

为什么会发生这种情况的任何建议?(我不认为这与我正在扩展的servlet有关)

这是applicationContext.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="dataServlet" class="com.mycom.util.DataServlet">
    <property name="dataSource" ref="dataSource" />
    <property name="test" value="dataSource" />
</bean>
Run Code Online (Sandbox Code Playgroud)

servlet

public class DataServlet extends DataSourceServlet {
...
@Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
        logger.log(Level.INFO, "Inj: datasrc");
    }
@Autowired
    public void setTest(String test) {
        this.test = test;
        logger.log(Level.INFO, "Set Test {0}", this.test);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在setTest设置了断点,它打破了@ pre-init.但是当实际对象被请求时.它不会破坏@testTest.

为什么会这样?(单例/范围问题有关吗?)

请指教!提前致谢!

Tom*_*icz 6

您有两个servlet实例:

  • 一个由Spring管理的,已经DataSource正确注入
  • 由Tomcat创建的第二个,它对Spring一无所知(并且没有DataSource)

实际上,如果您使用@Resource而不是@AutowiredTomcat(在7.0上测试)将会尖叫,DataSource而不是绑定到JNDI(这证明它是管理servlet生命周期的servlet容器).

您的问题是您希望将Spring bean注入完全超出Spring控件的对象.这个问题有几种解决方法:

如果你不想深入研究MVC,我会建议HttpRequestHandlerServlet.这里:1,2是一个例子(也应与的Servlet工作之前3.0)