gpt4 book ai didi

java - 非事务性方法也被代理调用,如何避免这种情况?

转载 作者:行者123 更新时间:2023-12-01 11:06:26 26 4
gpt4 key购买 nike

我是 Spring 新手,我发现了一个有趣的行为,但不知道如何解决它......我有一个类如下:

@组件公共(public)类 ScheduleService {

/** The Constant log. */
private static final Logger log = LoggerFactory.getLogger(ScheduleService.class);

/** The schedule repository. */
@Autowired
private ScheduleRepository scheduleRepository;

@Autowired
private PipelineService pipelineService;


private AtomicReference atomic_scheduler = new AtomicReference();

/**
* Instantiates a new schedule service.
*/
public ScheduleService() {
}

/**
* Starts the quarts scheduler instance
*
*/
public synchronized void start() {
....
}

public Scheduler getScheduler() {
start();
return (Scheduler) atomic_scheduler.get();
}

/**
* Creates the schedule.
*
* @param session the session
* @param schedule the Schedule
* @return the Schedule
*/
public Schedule createSchedule(Session session, Schedule schedule) throws Exception {

............ }

/**
* Gets the Schedule.
*
* @param session the session
* @param id the id
* @return the Schedule
*/
@Transactional(propagation=Propagation.REQUIRES_NEW, isolation=Isolation.READ_COMMITTED)
public Schedule getSchedule(Session session, String id) throws Exception {

...... }

/**
* Gets the Schedule given the Schedule name.
*
* @param session the session
* @param name the name of the Schedule to return
* @return the Schedule
*/
@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
public Schedule getScheduleByName(Session session, String name) throws Exception {
........
}

/**
*/
public Schedule updateSchedule(Session session, Schedule sch) throws Exception {

...... }}

我发现此类中的所有方法都是由代理调用的,但我不知道为什么...... APO 代理应该只调用“事务”方法吗?我该如何解决这个问题?我想要通过直接调用线程而不通过代理来调用非事务方法。

谢谢大家的建议。

最佳答案

基本上不可能只通过代理调用某些方法。

要实现 AOP 行为(在您的情况下为 @Transactional),Spring 必须围绕您的对象构建一个代理,以便它可以拦截带注释的方法的调用。为此,Spring 必须在各处注入(inject)代理而不是您的对象。

所以所有其他对象只知道代理。并且所有调用只能通过代理进行。

如何才能只让事务调用通过代理?这将需要大量的字节码操作来查找对对象上方法的所有调用,然后根据它们是否是事务性的来以某种方式开始重定向它们。还要记住 Spring 不仅支持单例 bean。对于一个类的多个实例,它还必须找出要委托(delegate)的对象。在任何地方注入(inject)代理并让 Java 从那里正常工作要容易得多。

如果您想了解更多详细信息,您可能需要查看java.lang.reflect.Proxy并尝试自己构建代理。这将使您了解 Java 动态代理实际上是如何工作的。 (如果我没有记错的话,Spring 默认情况下也使用此类作为其代理。)

关于java - 非事务性方法也被代理调用,如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com