a) 配合使用org.springframework.transaction.interceptor.TransactionInterceptor和org.springframework.orm.hibernate.HibernateTransactionManagerQ下面是spring reference的例?
This interceptor binds a new Hibernate Session to the thread before a method
call, closing and removing it afterwards in case of any method outcome.
If there already was a pre-bound Session (e.g. from HibernateTransactionManager,
or from a surrounding Hibernate-intercepted method), the interceptor simply
takes part in it.
]]>Spring控制反{(IoC)的理?/title>http://www.aygfsteel.com/terry711/articles/103639.htmlterryliuterryliuTue, 13 Mar 2007 14:13:00 GMThttp://www.aygfsteel.com/terry711/articles/103639.htmlhttp://www.aygfsteel.com/terry711/comments/103639.htmlhttp://www.aygfsteel.com/terry711/articles/103639.html#Feedback0http://www.aygfsteel.com/terry711/comments/commentRss/103639.htmlhttp://www.aygfsteel.com/terry711/services/trackbacks/103639.html 使用IoCQ对象是被动的接受依赖类Q而不是自׃动的L。容器在实例化的时候主动将它的依赖cL入给它。可以这L解:控制反{类的主动权转移到接口上Q依赖注入通过xml配置文g在类实例化时其依赖cL入。通过下面的实例来逐步的理解:
首先假设有一个需求,cBusiness需要调用类Dependency的方法f()Q按照日常的做法Q得C面的代码Q?br />//**cDependency** public class Dependency { public void f() {}; } //**cBusiness** public class Business { Dependency d; public Business() { d = new Dependency(); } public void doSth() { d.f(); } }
对上q实现做出如下修改: 首先Q将Business里的Dependency实例的获得该为setter方式Q其ơ,DependencycL为某个接口的实现。故可以得到下面新的代码Q?br />//**接口IDependency** public inte***ce IDependency { void f(); } //**cDependency** public class Dependency { public void f() {}; } //**cBusiness** public class Business { IDependency d; public Business() {} public void doSth() { d.f(); } public void setDependency(IDependency d) { this.d = d; } }
在新的代码中Q首先Business的变量d可以接收MIDependency的实例,另外QDependency的实例不是通过Business来获得,而是通过setter(也可以用构造器)来由外部传给它。这g跟我们往常的代码没什么不同,但这已经是一个良好的设计。关键就是Dependency的实例如何从外部注入lBusiness呢? q就要通过xml来实C?br /> 创徏一个SpringFirst.xmlQ进行简单的配置Q?br /><beans> <bean id = "dependency" class = "aopfirst.business.Dependency" /> <bean id = "business" class = "aopfirst.business.Business" > <property name = "dependency"> <ref bean = "dependency" /> </property> </bean> </beans> q个配置文g里将DependencycdBusinesscd入,q将Dependency作ؓBusiness的一个参数?br />
public class StartServer { public static void main(String [] args) { ClassPathResource cr = new ClassPathResource("SpringFirst.xml"); BeanFactory factory = new XmlBeanFactory(cr); Business b = (Business)factory.getBean("business"); b.doSth(); } }