弹簧依赖配置问题



大家好,

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

这是我的网络.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>`

这是我的应用程序上下文.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上下文.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;
    }
}

这是我的用户服务类

public class UserService {

    public User fetchUser(){
        User user = new User();
        user.setUserName("test");
        return user;
    }
}

您错过了HomeController中的@Autowired注释:

@Autowired
private UserService userService;
  1. 删除homeController豆定义。

由于您使用的是<context:component-scan base-package="controllers"/>因此无需声明homeController bean - 它将自动创建,因为它带有注释@Controller

  1. 自动将UserService连接到HomeController using @Autowired注释中。有 3 种方法可以做到这一点:
    • 现场注入:
@Autowired
private UserService userService;
  • 二传手注射
@Autowired
public void setUserService(UserService userService) {
    this.userService = userService;
}
  • 构造函数注入:
@Autowired
public HomeController(UserService userService) {
    this.userService = userService;
}

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

  1. 删除UserService吸气剂和二传手HomeController

最后,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());
    }
}

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

公共类用户服务 {

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

public User fetchUser(){
    User user = userDao.fetchUser();
    return user;
}

}

最新更新