Spring AOP configuration transactions do not work (Junit is used to test the service)

Source: Internet
Author: User

Today, I encountered a strange thing. I configured transactions in the Spring configuration file and performed transactions on all methods at the Service layer. However, when I tested one of the methods, it is found that it is not a transaction, and the first operation in it is completed, but the second operation fails. The reason is found. It turns out that the try and catch statement blocks are used inside this method, so that exceptions are caught internally. In Spring, transaction rollback is triggered by exceptions. That is to say, the servcie layer method cannot capture exceptions. It should be thrown up or not written (or thrown out of exceptions), so that Spring transactions will take effect.

 


The Spring configuration file is as follows:

<Bean id = "txManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager">
<Property name = "sessionFactory" ref = "mySessionFactory"/>
</Bean>
 
<Tx: advice id = "txAdvice" transaction-manager = "txManager">
<Tx: attributes> www.2cto.com
<Tx: method name = "*" propagation = "REQUIRED"/>
</Tx: attributes>
</Tx: advice>
 
<Aop: config>
<Aop: pointcut id = "productServiceMethods" expression = "execution (public * com. sq. hps. modules. *. service... * (..)"/>
<Aop: advisor advice-ref = "txAdvice" pointcut-ref = "productServiceMethods"/>
</Aop: config>

 

 

You can use Junit for testing:

Public class UserTest {

@ Test
Public void testAddBackRole (){

BackRole backRole = new BackRole ();
BackRole. setName ("test11 ");
BackRole. setDescription ("test ");
BackRole. setParkingIds ("");
String privilegeStr = "";

ApplicationContext ctx = new ClassPathXmlApplicationContext ("applicationContext. xml ");
UserService userService = (UserService) ctx. getBean ("userService ");
System. out. println (userService );
UserService. addBackRole (backRole, privilegeStr );

}
}


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.