在Spring中是否可以注入Servlet实例?下面是我写的一个servlet,想法是当请求提交到该servlet时,如果在Spring中进行了相关配置,那么该servlet的成员
message是否已经被初始化。
public class LoginServlet extends HttpServlet {
        private String message;
        public void setMessage(String message){this.message=message;} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
               PrintWriter out=response.getWriter();
       out.println("message:"+message);

} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
在applicationContext.xml的配置
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="loginServlet" class="com.hss.servlet.LoginServlet">
<property name="message" value="Hello world"/>
</bean>
</beans>
以上例子我试过了(当然环境已经搭建好了)不过获取不到message的值,提示错误是message值为null假如该servlet有个成员对象User user,且在配置文件中做了配置,那么可以使用WebApplicationContextUtil类的getWebApplicationContext()方法获取spring容器,然后getBean方法获得user的值,但是如果不用这种方法,直接
用以上例子的方法不行么?也就是说只要该servlet的成员变量(普通类型或者对象类型)设置了set方法,且在Spring配置文件中
配置了相应的bean,并在loginServlet中设置了相应的property属性,那么是否只要有请求到该servlet时,该servlet的成员
就会被Spring容器初始化了呢?望大家赐教。

解决方案 »

  1.   

    在serclet里给message提供get方法;
      

  2.   

    虽然你定义了类的实例变量private String message; 但是并没有它的get方法,spring就不能通过反射来取到message
      

  3.   

    一个注入实例 希望楼主可以感发
    <bean   id= "user " 
    class= "car.model.User "> 
    <property   name= "userName "> 
    <value> aaa </value> 
    </property> 
    </bean> 
    配置了一个id为user的bean,其类型为car.model.User,userName属性为aaa. <bean   id= "estimateControl " 
    class= "car.EstimateControl "> 
    <property   name= "user "> 
    <ref   bean= "user "   /> 
    </property> 
    </bean> 
    配置了一个id为estimateControl的bean,其属性user的值为前一个bean。
      

  4.   


    定义set,get方法。例:
    <bean id="constant" class="nx.flat.util.Constant">
    <property name="ICBCVALUE" value="4"></property>
    </bean>Constant.java
    private long ICBCVALUE;
    public long getICBCVALUE() {
    return ICBCVALUE;
    }
    public void setICBCVALUE(long icbcvalue) {
    ICBCVALUE = icbcvalue;
    }调用
     Constant con = (Constant) getBean("constant");
    con.getICBVALUE();