春季用于jdbctemplate和事务管理的Java配置 [英] Java configuration for jdbctemplate and transaction management in spring
问题描述
我正在使用具有Spring jdbc事务支持的spring jdbc.
I am using spring jdbc with spring jdbc transaction support.
这是我的配置.
@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@EnableGlobalMethodSecurity(securedEnabled = true)
@PropertySource(name = "props", value = { "classpath:common/jdbc.properties", "classpath:common/mail.properties",
"classpath:common/message.properties", "classpath:common/common.properties" })
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${jdbc.url}")
private String jdbcURL;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Value("${jdbc.driver}")
private String jdbcDriver;
/**
* configure jdbc datasource
*
* @return DataSource
*/
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(jdbcURL, jdbcUsername, jdbcPassword);
dataSource.setDriverClassName(jdbcDriver);
return dataSource;
}
/**
* configure jdbc template
*
* @return JdbcTemplate
*/
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
@Bean
public PlatformTransactionManager txManager() {
return new DataSourceTransactionManager(getDataSource());
}
}
使用此配置交易不适用于我.我不确定原因,但是我能理解的是-
With this configuration transaction doesn't work for me. I am not sure with the reason but what i could understand is following -
正如您所看到的jdbcTemplate()和txManager()一样,这两种方法都调用了getDataSource()方法,这又创建了jdbcDataSource.我认为在这两种方法中,我都将创建两个jdbc dataSource,因此jdbcTemplate和事务管理器都使用了两个不同的dataSource.
As you can see jdbcTemplate() and txManager() both the methods are calling getDataSource() method which inturn create jdbcDataSource. I think in both the method i am creating two jdbc dataSource, so jdbcTemplate and transaction manager both are using two different dataSource.
所以我的问题是-
- 是真的jdbcTemplate和transactionManager使用两个不同的数据源,还是@Bean可以处理这种情况.
- 如果它们都使用两个不同的dataSource,那么如何配置它们以使它们使用相同的dataSource.
我看到在xml中配置它很容易,但是使用java配置,我找不到同时使用jdbcTemplate和transactionManager的示例.
I can see it's easy to configure it in xml but with java configuration i couldn't find an example using both jdbcTemplate and transactionManager.
推荐答案
答案
- @Bean处理此问题.由于在类的顶部具有@Configuration,因此您将以完全(相对于lite)模式进行操作,因此Spring会拦截那些用Java @Bean注释的方法,并确保该方法仅被调用一次.顺便说一句,我将其称为dataSource()而不是getDataSource(),因为方法名称用于Bean名称.如有疑问,请进行一些日志记录,然后查看控制台进行确认.
- 问题2变得无关紧要.
为什么您的交易无效?很难说,因为您没有提供无法正常工作的完整上下文,但是需要考虑一些事项:
Why your transactions doesn't work? It's hard to tell since you are not providing the full context where it fails to work, but some things for considerations:
- 您忘记为方法/类添加@Transactional吗?
- 您正在使用一种不太常见的本机AspectJ编织方法(与更常见,更简单的基于JDK代理的方法相比).我没有用过,但是根据文档,您必须以不同的方式编译/构建代码,因为它不是纯Java方法.
这篇关于春季用于jdbctemplate和事务管理的Java配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!