Spring 从配置 java 文件中禁用 @Transactional

Spring Disable @Transactional from Configuration java file

我有一个用于两个不同应用程序的代码库。我的一些 spring 服务 类 有注释@Transactional。在服务器启动时,我想根据一些配置禁用@Transactional。

下面是我的配置Class。

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")

public class WebAppConfig {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(url);
        dataSource.setUsername(userId);
        dataSource.setPassword(password);

        return dataSource;
    }
    @Bean
    public PlatformTransactionManager txManager() {
         DefaultTransactionDefinition def = new DefaultTransactionDefinition();
         def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
            if(appName.equqls("ABC")) {
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);
                }else {
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                }
         CustomDataSourceTransactionManager txM=new CustomDataSourceTransactionManager(def);
         txM.setDataSource(dataSource());
    return txM;
    }


    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        return jdbcTemplate;
    }

}

我正在尝试验证 DataSourceTransactionManager 中的方法来实现功能。但它仍在尝试 commit/rollback 交易结束时的交易。由于没有可用的数据库连接,因此抛出异常。

如果我保留@Transactional(propagation=Propagation.NEVER),一切正常,但我无法修改它,因为另一个应用程序正在使用相同的代码库,在这种情况下这是必要的。

我想知道是否有一种方法可以在不修改@Transactional 注释的情况下从配置中完全禁用事务。

我不确定它是否可行,但您可以尝试实现自定义 TransactionInterceptor 并通过删除事务性内容来覆盖其将调用包装到事务中的方法。像这样:

public class NoOpTransactionInterceptor extends TransactionInterceptor {

    @Override
    protected Object invokeWithinTransaction(
        Method method, 
        Class<?> targetClass, 
        InvocationCallback invocation
    ) throws Throwable {
        // Simply invoke the original unwrapped code
        return invocation.proceedWithInvocation();
    }
}

然后在 @Configuration

之一中声明一个条件 bean
// assuming this property is stored in Spring application properties file
@ConditionalOnProperty(name = "turnOffTransactions", havingValue = "true")) 
@Bean   
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionInterceptor transactionInterceptor(
         /* default bean would be injected here */
         TransactionAttributeSource transactionAttributeSource
) {
    TransactionInterceptor interceptor = new NoOpTransactionInterceptor();
    interceptor.setTransactionAttributeSource(transactionAttributeSource);
    return interceptor;
}

您可能需要额外的配置,我现在无法验证