日期:2014-05-17  浏览次数:20890 次

spring声明式事务,service层必须在ioc容器中声明?
各位,小弟在学习spring+hibernate 声明式事务时,发现一个问题, 做了两种测试 

public class DefaultFooService implements FooService { 
   private static FooDaoHibernate fooDaoHibernate; 
   private static RelationshipDaoHibernate relationshipDaoHibernate; 
   private static ApplicationContext ctx = null; 
   private static SessionFactory sessionFactory = null; 

   ... 


1. 建立一个普通的 java project 
x.y.services 包下有 applicationContext.xml, DefaultFooService.java, 在applicationContext.xml中对DefaultFooService进行声明式事务,并注入 DefaultFooService 
运行后成功实现事务管理 

<bean id="fooService" class="x.y.service.DefaultFooService"> 
    <property name="fooDaoHibernate" ref="fooDao" /> 
    <property name="relationshipDaoHibernate" ref="relationshipDao" /> 
</bean> 
<bean id="fooDao" class="x.y.service.FooDaoHibernate"> 
    <property name="sessionFactory" ref="sessionFactory" /> 
</bean> 
<bean id="relationshipDao" class="x.y.service.RelationshipDaoHibernate"> 
    <property name="sessionFactory" ref="sessionFactory" /> 
</bean> 

2. 建立一个 web dynamic project 
在applicationContext.xml中对DefaultFooService进行声明式事务,但不注入 DefaultFooService,没有上面的代码,而是在 DefaultFooService.java中, 
public void init() {  
    System.out.println("init...");  
    ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
    sessionFactory = (SessionFactory)ctx.getBean("sessionFactory");  
    if(sessionFactory == null) {  
        System.out.println("sessionFactory is null");  
    }  
    fooDaoHibernate = new FooDaoHibernate();  
    if(fooDaoHibernate == null) {  
        System.out.println("fooDaoHibernate in init() is null");  
    }  
    fooDaoHibernate.setSessionFactory(sessionFactory);  
    relationshipDaoHibernate = new RelationshipDaoHibernate();  
    relationshipDaoHibernate.setSessionFactory(sessionFactory);  
}  
同时在 spring-servlet.xml中 
<bean id="fooService" class="x.y.services.DefaultFooService" init-method="init"></bean>  
spring 事务管理

------解决方案--------------------
如果你的bean都没有在spring的容器里你想让spring来针对切面编程?这怎么可能,要知道,spring是通过动态代理(有接口时)或继承(没接口时)来对原始类方法进行包装后进行的.不然怎么进行aop?