2013-03-08 71 views
3

我试图简单地试用Spring,但我似乎失去了一些东西。它似乎加载春天和豆很好,但是当涉及到注入这些豆与自动装配,它不起作用。有人有线索吗?春天不注射豆,我做错了什么?

的web.xml中对Spring和mainServlet的一部分:

<welcome-file-list> 
     <welcome-file>/login.jsp</welcome-file> 
    </welcome-file-list> 

    <!-- Spring Dependency Injection --> 

    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/applicationContext.xml</param-value> 
    </context-param> 

    <listener> 
     <listener-class> 
      org.springframework.web.context.ContextLoaderListener 
    </listener-class> 

<!-- Login Filter --> 
<filter> 
    <filter-name>LoginFilter</filter-name> 
    <filter-class>com.nortal.pirs.presentation.web.LoginFilter</filter-class> 
    <init-param> 
     <param-name>secretParameter</param-name> 
     <param-value>8392</param-value> 
    </init-param> 
</filter> 

<filter-mapping> 
     <filter-name>LoginFilter</filter-name> 
     <url-pattern>/MainServlet</url-pattern> 
     <servlet-name>MainServlet</servlet-name> 
</filter-mapping> 

<!-- Main Servlet --> 
<servlet> 
<servlet-name>MainServlet</servlet-name> 
<servlet-class>com.nortal.pirs.presentation.web.MainServlet</servlet-class> 

<servlet-mapping> 
    <servlet-name>MainServlet</servlet-name> 
    <url-pattern>/main/*</url-pattern> 
</servlet-mapping> 

Spring应用程序上下文文件(虽然我觉得我也装好了有太多不必要的废话,但它绝望,因为它不工作):

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.1.xsd"> 

    <context:annotation-config /> 

    <!-- Turn on AspectJ @Configurable support --> 
    <context:spring-configured /> 

    <context:component-scan base-package="com.nortal.pirs.test.independent" /> 
    <context:component-scan base-package="com.nortal.pirs.businesslogic.logic" /> 
    <context:component-scan base-package="com.nortal.pirs.presentation.vaadin" /> 
    <context:component-scan base-package="com.nortal.pirs.presentation.vaadin.views" /> 
    <context:component-scan base-package="com.nortal.pirs.presentation.web" /> 

    <!-- Turn on @Autowired, @PostConstruct etc support --> 
    <bean 
     class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> 
    <bean 
     class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> 

</beans> 

UserManagerLogic(即在MainServlet被注入与@Autowired后的豆):

@Component("UserManager") 
public class UserManagerLogic implements UserManagerInterface { 

MainServlet:

@Service 
public class MainServlet extends HttpServlet { 

    @Autowired 
    @Qualifier("UserManager") 
    private UserManagerInterface userManager; 
    Logger log; 

    public MainServlet() { 
     log = Logger.getLogger(getClass()); 
    } 

    public boolean userLoggedIn(String username, String password) {  
     return SecurityManager.getInstance().credentialsValid(username, password); 
    } 

    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
     processRequest(req, resp); 
    } 

    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
     processRequest(req, resp); 
    } 

    public void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 

     HttpSession session = ((HttpServletRequest) request).getSession(); 

     String username = (String) session.getAttribute("username"); 
     boolean authenticated = (boolean) session.getAttribute("authenticated"); 

     User user = userManager.getUserByEmail(username); 

     WelcomeGenerator welcomeGenerator = new WelcomeGenerator(); 

     if (authenticated) { 
      generateResponse(response, welcomeGenerator.WelcomeMessage(user), "The secret code is " + session.getAttribute("secretParameter")); 
     } else { 
      generateResponse(response, welcomeGenerator.wrongCredentialsMessage(username), "Secret code is hidden, because authentication failed"); 
     } 
    } 

    public void generateResponse(HttpServletResponse response, String welcomeMessage, String additionalData) throws IOException {  
     HtmlGenerator generator = new HtmlGenerator("PIRS"); 
     response.setContentType("text/html"); 
     PrintWriter out = response.getWriter(); 

     out.write(generator.printHeader()); 
     out.write(generator.printCenter(welcomeMessage)); 
     out.write(generator.printCenter(additionalData)); 
     out.write(generator.printFooter()); 
    } 

    public UserManagerInterface getUserManager() { 
     return userManager; 
    } 

    public void setUserManager(UserManagerInterface userManager) { 
     this.userManager = userManager; 
    }    
} 

而结果是在一个空指针异常当然是调用用户管理器,这应该是由Spring注入的?

java.lang.NullPointerException 
    at com.nortal.pirs.presentation.web.MainServlet.processRequest(MainServlet.java:58) 
    at com.nortal.pirs.presentation.web.MainServlet.doPost(MainServlet.java:47) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) 

但是,Spring的确加载了它只注入它们的bean,并没有抛出任何错误,为什么?

2013-03-08 03:48:42,834 [localhost-startStop-1] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.s[email protected]6a4ac9fb: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.config.internalBeanConfigurerAspect,mainController,SecurityManager,**UserManager**,VisitManager,**mainServlet**,org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#0,org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#0,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy 
+0

你为什么不使用控制器,而不是servlet的 – 2013-03-08 03:02:10

+0

'@ service'注释并不意味着对servlet.Check这out.Should完成与你的问题相同.http://stackoverflow.com/questions/14283750/instantiationexception-using-spring-injection – SRy 2013-03-08 06:37:56

回答

1

您的servlet不是@Configurable。由于它的生命周期不受Spring的控制,所以这是唯一可以让它自动装配的方法。

哦,你的servlet绝对不是@Service

+0

不止这些。你的servlet不是由spring管理的,所以它不能注入其他bean。 – 2013-03-08 02:07:13

+0

@Sotirios:这是不正确的。请参阅[“使用AspectJ向Spring依赖注入域对象”](http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable)。它针对域对象,但适用于任何事情。 – 2013-03-08 02:10:25

+0

在这个问题的上下文中,servlet容器将实例化他的'MainServlet',所以Spring如何知道自动装入任何东西? – 2013-03-08 03:40:55

0

那是因为Servlet是由Spring Container管理的。 Servlet由Servlet容器管理。

但幸运的是,Spring提供了一种实用方法来获取SpringApplicationContext从Servlet中获取bean。 这是使用WebApplicationContextUtils

示例代码

ApplicationContext ctx = 
        WebApplicationContextUtils. 
          getWebApplicationContext(session.getServletContext()); 
UserManagerInterface userManager = (UserManagerInterface)ctx.getBean("UserManager");