一,在监听器中读取不到web-inf下的spring-root.xml文件解决方法
用ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring-root.xml");
和ApplicationContext applicationContext=new FileSystemXmlApplicationContext("web/WEB-INF/spring-root.xml");
都会报找不到相关文件
后来发现: ==LoopimgService loopimgService=ContextLoaderListener.getCurrentWebApplicationContext().getBean(LoopimgService.class);==可以直接获取到spring-root下注册过的bean组件
web.xml配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-root.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
监听器:
package com.study.listener;
import com.study.service.LoopimgService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener()
public class InitListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext=servletContextEvent.getServletContext();
servletContext.setAttribute("root",servletContext.getContextPath());
servletContext.setAttribute("js",servletContext.getContextPath()+"/resources/js");
servletContext.setAttribute("image",servletContext.getContextPath()+"/resources/image");
servletContext.setAttribute("upload",servletContext.getContextPath()+"/resources/upload");
// ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring-root.xml");
LoopimgService loopimgService=ContextLoaderListener.getCurrentWebApplicationContext().getBean(LoopimgService.class);
// =applicationContext.getBean(LoopimgService.class);
servletContext.setAttribute("imgList",loopimgService.initData());
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
二,Could not obtain transaction-synchronized Session for current thread问题:
可以看这篇文章,详细解释了此问题
但是并未解决我的问题(问题不同,但上面的可以解决大部分的问题)
这篇解决了我的问题
真正解决了我遇到的问题
文章截取:
我们在Spring IOC容器里声明的SessionFactory这个bean也创建了两个实例。问题可能就是因为创建了两个SessionFactory的实例,所以不能获取当前线程的Session。
此时只要在springmvc.xml扫描<context:component-scan>
节点加上use-default-filters=“false” 这个属性。就可以了。因为不加这个它还是会使用默认的过滤器。还是会扫描到其他的Spring IOC容器中的bean
我的spring-mvc.xml配置
<!--启动注解扫描-->
<context:component-scan base-package="com.study" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
</context:component-scan>