Spring依赖配置问题

时间:2014-12-19 10:52:52

标签: spring configuration dependency-injection

大家好,

我是Spring的新手,目前我正在开发一个使用Spring MVC和Spring依赖注入的Web项目。我有三节课。 UserService,HomeController和User。在HomeController中,我调用UserService的fetchUser方法,该方法返回一个新的User类实例。这是一个简单的逻辑,我用来重现我的真实项目问题。我没有在这个简单的项目中使用任何数据库。当我调用fetchUserMethod时,我得到一个NullPointerException。我正在使用Glassfish 4.0。请你帮助我好吗 ?         谢谢!

这是我的web.xml

        `<?xml version="1.0" encoding="UTF-8"?>
        <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

            <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
            <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring/aplicationContext.xml</param-value>
            </context-param>

            <!-- Creates the Spring Container shared by all Servlets and Filters -->
            <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
            </listener>

            <!-- Processes application requests -->
            <servlet>
                <servlet-name>appServlet</servlet-name>
                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                <init-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
                </init-param>
                <load-on-startup>1</load-on-startup>
            </servlet>

            <servlet-mapping>
                <servlet-name>appServlet</servlet-name>
                <url-pattern>/</url-pattern>
            </servlet-mapping>

        </web-app>`

这是我的applicationContext.xml

         <?xml version="1.0" encoding="UTF-8"?>
        <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.xsd">

            <!-- Root Context: defines shared resources visible to all other web components -->

            <bean id="userService" class="services.UserService"/>

            <bean id="homeController" class="controllers.HomeController">
                <property name="userService" ref="userService"/>
            </bean>

        </beans>

这是我的servlet-context.xml

    <?xml version="1.0" encoding="UTF-8"?>

    <beans:beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">


        <!-- Enables the Spring MVC @Controller programming model -->
        <mvc:annotation-driven />

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>

        <context:component-scan base-package="controllers"/>

    </beans:beans>

这是我的HomeController类

@Controller
public class HomeController {

    private UserService userService;

    @RequestMapping(value = "/home")
    public ModelAndView homePage(HttpServletRequest request, HttpServletResponse response, HttpSession session){



        User user = userService.fetchUser();

        return new ModelAndView("home", "displayName", user.getUserName());
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}

这是我的用户类

public class User {

    private String userName;

    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

这是我的UserService类

public class UserService {


    public User fetchUser(){

        User user = new User();
        user.setUserName("test");

        return user;
    }
}

3 个答案:

答案 0 :(得分:1)

您遗漏了@Autowired中的HomeController注释:

@Autowired
private UserService userService;

答案 1 :(得分:0)

  1. 删除homeController bean定义。
  2. 由于您使用<context:component-scan base-package="controllers"/>,因此无需声明homeController bean - 它将自动创建,因为它已使用注释@Controller进行注释。

    1. UserService自动装入HomeController using @ Autowired`注释。有3种方法可以做到:
      • 现场注入:
    2. @Autowired
      private UserService userService;
      
      • setter injection
      @Autowired
      public void setUserService(UserService userService) {
          this.userService = userService;
      }
      
      • 构造函数注入:
      @Autowired
      public HomeController(UserService userService) {
          this.userService = userService;
      }
      

      首选方法是始终使用构造函数注入

      1. 删除UserService中的HomeController getter和setter。
      2. 最后,HomeController类应如下所示:

        @Controller
        public class HomeController {
            private final UserService userService;
        
            @Autowired
            public HomeController(UserService userService) {
                this.userService = userService;
            }
        
            @RequestMapping(value = "/home")
            public ModelAndView homePage(HttpServletRequest request, HttpServletResponse response, HttpSession session){
                User user = userService.fetchUser();
        
                return new ModelAndView("home", "displayName", user.getUserName());
            }
        }
        

答案 2 :(得分:0)

这样Eclipse标记了带错误的默认构造函数行。如果我删除默认构造函数glassfish说它无法初始化UserService,因为没有默认构造函数。

公共类UserService {

public UserService(){}

private final UserDao userDao;

@Autowired
public UserService(UserDao userDao){
    this.userDao = userDao;
}


public User fetchUser(){

    User user = userDao.fetchUser();

    return user;
}

}