Spring框架入门,tomcat启动成功,但是出现关于上下文加载异常?

这是一个制作登陆页面的小练习,大概长这样
图片说明

错误信息是在Server startup后立马就出现的,还没来得及访问index.jsp呢!求指点,谢谢。

web.xml存放在WEB-INF文件夹下

图片说明

错误信息:

七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server version:        Apache Tomcat/8.5.42
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server built:          Jun 4 2019 20:29:04 UTC
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server number:         8.5.42.0
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Name:               Windows 10
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Version:            10.0
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Architecture:          amd64
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Java Home:             C:\Program Files\Java\jdk1.8.0_201\jre
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM Version:           1.8.0_201-b09
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM Vendor:            Oracle Corporation
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_BASE:         D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_HOME:         D:\apache-tomcat-8.5.42
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.base=D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.home=D:\apache-tomcat-8.5.42
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dwtp.deploy=D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Djava.endorsed.dirs=D:\apache-tomcat-8.5.42\endorsed
七月 20, 2019 3:20:35 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dfile.encoding=UTF-8
七月 20, 2019 3:20:35 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: Loaded APR based Apache Tomcat Native library [1.2.21] using APR version [1.6.5].
七月 20, 2019 3:20:35 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
七月 20, 2019 3:20:35 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
七月 20, 2019 3:20:35 下午 org.apache.catalina.core.AprLifecycleListener initializeSSL
信息: OpenSSL successfully initialized [OpenSSL 1.1.1a  20 Nov 2018]
七月 20, 2019 3:20:35 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8080"]
七月 20, 2019 3:20:36 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
七月 20, 2019 3:20:36 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-nio-8009"]
七月 20, 2019 3:20:36 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
七月 20, 2019 3:20:36 下午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1265 ms
七月 20, 2019 3:20:36 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Catalina]
七月 20, 2019 3:20:36 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.42
七月 20, 2019 3:20:39 下午 org.apache.catalina.core.ApplicationContext log
信息: No Spring WebApplicationInitializer types detected on classpath
七月 20, 2019 3:20:39 下午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
七月 20, 2019 3:20:39 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
七月 20, 2019 3:20:42 下午 org.apache.catalina.core.StandardContext listenerStart
严重: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersService' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'usersMapper' of bean class [yan.ibbie.service.impl.UsersServiceImpl]: Bean property 'usersMapper' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1718)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1433)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4770)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'usersMapper' of bean class [yan.ibbie.service.impl.UsersServiceImpl]: Bean property 'usersMapper' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)
    at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426)
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278)
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1714)
    ... 22 more

七月 20, 2019 3:20:42 下午 org.apache.catalina.core.StandardContext startInternal
严重: One or more listeners failed to start. Full details will be found in the appropriate container log file
七月 20, 2019 3:20:42 下午 org.apache.catalina.core.StandardContext startInternal
严重: Context [/SpringLogin] startup failed due to previous errors
七月 20, 2019 3:20:42 下午 org.apache.catalina.core.ApplicationContext log
信息: Closing Spring root WebApplicationContext
七月 20, 2019 3:20:42 下午 org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
警告: The web application [SpringLogin] registered the JDBC driver [com.mysql.cj.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
七月 20, 2019 3:20:42 下午 org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
警告: The web application [SpringLogin] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144)
 com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:85)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
 java.lang.Thread.run(Thread.java:748)
七月 20, 2019 3:20:42 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]
七月 20, 2019 3:20:42 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-nio-8009"]
七月 20, 2019 3:20:42 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 5949 ms
七月 20, 2019 3:20:45 下午 org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
信息: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1384)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1034)
    at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.checkThreadContextClassLoader(AbandonedConnectionCleanupThread.java:117)
    at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:84)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)


web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <!-- 设置Spring配置文件路径 -->
    <!-- 当tomcat加载web.xml时,会把Spring配置文件信息存放到application对象 -->
    <!-- WebApplicationContext是ApplicationContext的子接口 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 加载Spring配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

applicationContext.xml的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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 数据源封装类 -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="147852369"/>
    </bean>
    <!-- SqlSessionFactory -->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
    </bean>
    <!-- 扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="factory"/>
        <property name="basePackage" value="yan.ibbie.mapper"/>
    </bean>

    <!-- 创建UsersService的实现类,其中usersMapper是Spring自动创建的bean -->
    <bean id="usersService" class="yan.ibbie.service.impl.UsersServiceImpl">
        <property name="usersMapper" ref="usersMapper"/>
    </bean>
</beans>

index.jsp页面如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function(){
    $("a").click(function(){
        $("img").attr("src","validcode?date="+new Date());
        return false;
    })
})
</script>
</head>
<body>
${error }
<form action="Login" method="post">
    用户名:<input type="text" name="username" /><br>
    密码:<input type="password" name="password" /><br>
    验证码:<input type="text" size="1" name="code"/><img src="validcode" width="80" height="40"/><a href="">看不清</a><br>
    <input type="submit" value="登陆" /><input type="reset" value="重置" />
</form>
</body>
</html>

出错的是LoginServlet中一堆aaaaa那行,LoginServlet如下:

package yan.ibbie.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import yan.ibbie.pojo.Users;
import yan.ibbie.service.UsersService;
import yan.ibbie.service.impl.UsersServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UsersService usersService;

    @Override
    public void init() throws ServletException {
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+getServletContext());
        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        usersService = ac.getBean("usersService",UsersServiceImpl.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeSession = session.getAttribute("validcode").toString();
        if (codeSession.equals(code)) {
            Users users = new Users();
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            users.setUsername(username);
            users.setPasserword(password);
            Users user = usersService.login(users);
            if (user!=null) {
                resp.sendRedirect("main.jsp");
            }else {
                req.setAttribute("error", "用户名和密码不正确");
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            }

        }else {
            req.setAttribute("error", "验证码不正确");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }

    }

}

1个回答

自问自答

主要问题不在贴出来的代码上。
而是因为我没有为UsersServiceImpl中的usersMapper添加get/set方法,导致创建applicationContext.xml中的usersService这个bean的时候,注入usersMapper失败。

敲黑板!!!Spring属性注入usersMapper是依赖于get/set方法的!!!

现在突然又觉得我的答案不是很对。。。。。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问