我正在研究在Swing应用程序上使用Spring的可能性,应用MVC概念。
现在我正在尝试创建一个@Transactional方法,但它不会启动事务。
这是我的代码:
@Component
public class MainFormController {
@Autowired
private MainFormFrameView view;
@Autowired
private MyService service;
public MainFormController() {
view.button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doSomethingInTransaction();
}
});
}
@Transactional
public void doSomethingInTransaction() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("No active transaction!!!!");
}
service.doSomethingOverTheTransaction();
}
}
这是我的配置:
@Configuration
@ComponentScan(basePackages = "br.com.jjw.pdv")
@EnableTransactionManagement
public class AppContextConfiguration {
@Bean
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource ret = new ComboPooledDataSource();
ret.setDriverClass(jdbcDriver.class.getName());
ret.setJdbcUrl("jdbc:hsqldb:file:dados.hsql");
ret.setUser("sa");
ret.setPassword("");
return ret;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException {
LocalContainerEntityManagerFactoryBean ret = new LocalContainerEntityManagerFactoryBean();
ret.setDataSource(dataSource());
ret.setJpaDialect(jpaDialect());
EclipseLinkJpaVendorAdapter adapter = new EclipseLinkJpaVendorAdapter();
adapter.setDatabase(Database.HSQL);
ret.setJpaVendorAdapter(adapter);
ret.setPersistenceXmlLocation("classpath:META-INF/persistence.xml");
ret.setPersistenceUnitName("jjw-pdv-unit");
ret.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return ret;
}
@Bean
public JpaDialect jpaDialect() {
return new EclipseLinkJpaDialect();
}
@Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
@Bean
public JpaTransactionManager transactionManager() throws PropertyVetoException {
JpaTransactionManager ret = new JpaTransactionManager();
ret.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
ret.setJpaDialect(jpaDialect());
return ret;
}
}
当我点击按钮时,doSomethingInTransaction()方法引发了我的异常:
IllegalStateException("No active transaction!!!!");
为什么?
答案 0 :(得分:1)
Spring AOP是基于代理的,不建议内部调用。
您需要在弹簧提供的代理上进行调用,例如
SomeTransactionalBean bean =
applicationContext.getBean(SomeTransactionalBean.class);
bean.doSomethingInTrasanction();
例如,将@Transactional
注释放在服务方法上。