Jewel Jose
Jewel Jose

Reputation: 71

Spring @Transactional annotation making my class not able to Autowire

I have a class SaveRoute which has got an auto-wired property SaveProcessor. This SaveProcessor class has got a method which is annotated with @Transactional annotation. When I try to run my application, Java is throwing an exception that bean SaveProcessor dependency injection failed. When I remove @Transactional annotation from SaveProcess class method, it is working fine.

SaveRoute

public class SaveRoute implements RouteBuilder{
    @Autowired
    private SaveProcessor saveProcessor;
}

SaveProcessor

public class SaveProcessor implements Processor{

  @Override
  public void Process(Exchange exchange){
    this.save();
  }
  @Transactional
  public void Save(){

  }
}

It would be great if someone could help me on this. @Transactional making SaveProcessor class not a candidate for auto wiring.

Upvotes: 2

Views: 2041

Answers (3)

rnemykin
rnemykin

Reputation: 56

agree with Spring @Transactional annotation making my class not able to Autowire answer, it is a good practice to autowire by interface, when you set

@Transactional

spring make proxy of your SaveProcessor object, because it implements Processor spring will use DynamicProxy. so you don't have a bean with class SaveProcessor in context, you have a bean with calss Proxy$.. wich implement intarface Processor.

that's why spring can't find a candidate.

it's not a problem if you have more than one implementations of Processor, just use

@Qualifier

, or autowiring by beanName. in your case

@Autowired
private Processor saveProcessor;

will be work, beacause bean has name saveProcessor

Upvotes: 1

Jewel Jose
Jewel Jose

Reputation: 71

I was able to figure out a solution. Adding

@Scope( proxyMode = ScopedProxyMode.TARGET_CLASS )

on top of my SaveProcessor class resolved my issue.

I cannot use

@Autowire public Processor SaveProcessor;

This is because there are mulpile implementation for Processor in my application.

Upvotes: 0

andrii
andrii

Reputation: 1388

You should use Processor interface instead of SaveProcessor concrete class when autowiring that kind:

@Autowired
private Processor saveProcessor;

Upvotes: 0

Related Questions