在Spring注解配置中,@Transaction和@Service一起使用的问题

3
我不太理解。使用@Serviced标记并由@ComponentScan在应用程序上下文中注册的bean是否通过@Transaction注释进行事务支持代理?
这样做可以正常工作:
    public class LocationManagerImpl implements LocationManager {

        @Transactional
        public void saveLocation(Location location) {

        }

    }

//config class

@Bean
public LocationManager locationManager() {
    return new LocationManagerImpl();
}

并且这个不行:

@Service
public class LocationManagerImpl implements LocationManager {

    @Transactional
    public void saveLocation(Location location) {

    }

}

2
@ComponentScan注解用于@Configuration类。您的应用程序上下文中是否有context:component-scan? - jeff
当您使用第二种方法并尝试从上下文中获取LocationManager时,您是否有一个?它是否存在但仅未代理事务?还是完全缺失? - jeff
@jeff,它不是丢失了,也没有为交易代理。 - Alexander Camperov
@BorisTreukhov 这是一个Web应用程序。配置由在web.xml中定义的ContextLoaderListener加载。 - Alexander Camperov
请检查您的服务是否在-servlet.xml中被自动扫描(stackoverflow.com/questions/3652090/difference-between-applicationcontext-and-spring-servlet-xml-in-spring)。否则AOP将无法工作。 - Boris Treukhov
显示剩余4条评论
1个回答

3
问题可能是您的带有@Transactional注释的类位于Servlet上下文中。如果您的servlet应用程序上下文配置中有<context:component-scan>,而Spring AOP拦截器在根应用程序上下文中进行配置,则可能会发生这种情况。
解决方法是将带有@Service注释的类移动到根Web应用程序上下文中。
请参见Spring @Transactional not working
Servlet和Web App Root上下文之间的区别:Difference between applicationContext.xml and spring-servlet.xml in Spring Framework


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接