我有一个@Transactional @Controller
,但它的方法正在被 Spring MVC 框架调用而没有事务。在异常跟踪中,我没有找到拦截调用的事务顾问:
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
org.example.businesslogic.MyController.userLoggedIn(SwiperRest.java:48)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
Run Code Online (Sandbox Code Playgroud)
另一方面,日志清楚地表明控制器方法被检测为事务性的:
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'metaDataSourceAdvisor'
DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'MyController.userLoggedIn' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
DEBUG o.s.a.f.a.InfrastructureAdvisorAutoProxyCreator - Creating implicit proxy for bean 'myController' with 0 common interceptors and 1 specific interceptors
DEBUG o.s.a.f.CglibAopProxy …
Run Code Online (Sandbox Code Playgroud) 上下文:
我从基于XML的Spring配置切换到了基于Java的配置.我的应用程序有一个基于JSP的Web层,Spring MVC,Spring Security和Hibernate作为持久性提供程序.
我设法在不同的配置类中分离整个XML配置:
WebConfig
- 用于Spring MVC配置;
PersistenceConfig
- 正如名称所述 - 用于JPA配置;
ServiceConfig
- 仅适用于@Service和@Component注释类;
SecurityConfig
- 用于Spring安全配置.
对于应用程序初始化,我有SecurityInitializer
和WebAppInitializer
类.
这是一些代码:
WebConfig
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.demo.app.web"})
public class WebConfig extends WebMvcConfigurerAdapter { /* Bean initialization */ }
Run Code Online (Sandbox Code Playgroud)
PersistenceConfig
@Configuration
@ComponentScan(basePackages = {"com.demo.app.dao"})
@EnableTransactionManagement(mode = AdviceMode.PROXY, proxyTargetClass = true)
public class PersistenceConfig { /* Bean initialization */ }
Run Code Online (Sandbox Code Playgroud)
ServiceConfig
@Configuration
@ComponentScan(basePackages = {"com.demo.app.service", "com.demo.app.component"})
public class ServiceConfig { /* Bean initialization */ }
Run Code Online (Sandbox Code Playgroud)
SecurityConfig
@Configuration …
Run Code Online (Sandbox Code Playgroud) 我正在尝试配置spring安全注释,我已经设法在xml中设置spring安全配置(由intercept-url元素配置),但现在我想在我的bean中使用安全注释.但是在尝试访问安全控制器方法而没有记录时,完全忽略了安全注释.这是我的控制器bean:
package com.bill.controllers;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
@Secured({"ROLE_USER"})
@RequestMapping("/index.html")
public String main(ModelMap model) {
model.addAttribute("test", "test");
return "main";
}
}
Run Code Online (Sandbox Code Playgroud)
和登录控制器:
package com.bill.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(ModelMap model) {
return "login";
}
}
Run Code Online (Sandbox Code Playgroud)
和配置:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>tests</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-servlet.xml, …
Run Code Online (Sandbox Code Playgroud) 我有一个问题,Spring将DAO对象的代理注入到服务中,但是这个服务被注入到控制器中它是具体的类.这不允许我使用服务范围的事务并分别为每个DAO调用启动事务.这是我期望的行为.
组态:
Controller是带有@Controller注释和构造函数DI的类.
服务:
@Component @Transactional public class UserServiceImpl implements UserService { ...}
道:
@Component @Transactional public class UserDaoImpl implements UserDao {
JPA配置:
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="xxxPersistenceUnit"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven />
Run Code Online (Sandbox Code Playgroud)
任何人都知道为什么会这样?
在eclipse中使用STS来创建一个mvc项目我注意到servlet-context.xml似乎被编写为在根上下文和dispatcherservlet Context中使用.我这样说是因为我注意到上下文:组件扫描在其中,它通常被加载到根上下文中,但它被加载到dispatcherservlet上下文中.我还注意到一个样品的Spring MVC/JPA项目- http://duckranger.com/2012/04/spring-mvc-3-x-with-sts-tutorial-part-iii-add-some-jpa/ -特异将servlet-context.xml加载到两个上下文中.我认为这个想法是在上下文之间保持清晰的分离.谁可以给我解释一下这个?
目前,我需要将一个大的json对象发送到ajax请求.为此我使用以下控制器方法,它工作正常.
@RequestMapping(method = RequestMethod.POST,params = {"dynamicScenario"})
@ResponseBody
public String getDynamicScenarioData(@RequestParam Map<String, String> map) throws JsonParseException, JsonMappingException, IOException
{
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String,Object> queryParameters = mapper.readValue(map.get("parameters") , Map.class);
Map<String, Object> getData = service.runDynamicScenario(queryParameters, map.get("queryString"));
return writer.writeValueAsString(getData); //here java throws java.lang.OutOfMemoryError: Java heap space memory
}
Run Code Online (Sandbox Code Playgroud)
更新:我的ajax是:
$.ajax({
type: "POST",
url: "dynamicScenario.htm",
data : tags,
dataType: "json",
success: function(data){});
Run Code Online (Sandbox Code Playgroud)
我的DispatcherServlet设置:
public class ApplicationInitializer implements WebApplicationInitializer
{
public void onStartup(ServletContext servletContext) throws
ServletException
{
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ApplicationConfig.class); …
Run Code Online (Sandbox Code Playgroud) 每个函数的目的是什么。为什么spring给配置类赋予了两种不同的功能?我对两者感到困惑,我应该使用哪一个?
我创建了一个使用一些 Autowired 字段的 servlet 过滤器。为了使它工作,我DelegatingFilterProxy
在 web.xml 中声明了它。在此过滤器之前,我的整个 spring 配置都在,dispatcher-servlet.xml
但由于某种原因,此过滤器的声明 bean 在 dispacher-servlet 中不起作用。所以,我在applicationContext.xml
. 然后它开始工作,但过滤器内的 Autwired 字段然后抛出null
. 为了解决它,我移动了
<context:component-scan base-package="com.myproj.abc" />
Run Code Online (Sandbox Code Playgroud)
到 applicationContext,过滤器开始工作,但我的控制器类定义的 url 路径不再映射。所以我还需要在 applicationContext 中拉出以下两行
<mvc:default-servlet-handler />
<mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)
这解决了这个问题。但我想知道这是所有这些代码的正确位置吗?因为 Spring 安全性以及静态资源和视图映射所有这些代码都在调度程序中。在我的另一个项目中,我遇到了同样的问题,我确实这样做了,仅在 applicationContext 中声明了以下行
<context:component-scan base-package="com.myproj.abc" />
Run Code Online (Sandbox Code Playgroud)
在调度程序 servlet 中,我将组件扫描包更改为仅控制器,并将所有其他代码仅保留在那里(在调度程序中)
<context:component-scan base-package="com.myproj.abc.controller" />
Run Code Online (Sandbox Code Playgroud)
任何人都可以请教我这种混乱。
spring ×7
java ×6
spring-mvc ×6
ajax ×1
annotations ×1
jackson ×1
jpa ×1
json ×1
security ×1
servlet-3.0 ×1
spring-boot ×1
spring-jdbc ×1
transactions ×1