Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Service and @Scope("prototype") together

I have a service class with @Service and @Scope("protoype"). I want this service to behave like prototype in the controller class. Here is how I use it:

@Controller
@RequestMapping(value="/")
public class LoginController {
  @Autowired
  private EmailService emailService;

  @RequestMapping(value = "/register", method = RequestMethod.POST)
  public String register(){
    System.out.println(emailService);
    emailService.sendConfirmationKey();
  }
  @RequestMapping(value = "/resetKey", method = RequestMethod.POST)
    System.out.println(emailService);
    emailService.sendResetKey();
}

Here is the service class:

@Service
@Scope("prototype")
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;

    public void sendConfirmationKey(){
    ...
    }
    public void sendResetKey(){
    ...
    }
}

I run spring boot using autoconfiguration property. I compare whether 'emailService' object is the same or not, and I get the same one object. It means that @Scope("prototype") does not work as expected with @Service. Do you see anything wrong here? Did I forget a few more codes to add?

Edit: Replying to @Janar, I do not want to use additional codes to make it work such as WebApplicationContext property and extra method to create. I know that there is a shorter way using only annotation.

like image 690
Eric Avatar asked Oct 19 '25 04:10

Eric


1 Answers

You must specify the proxy mode in the scope annotation.

This should do the trick:

@Service 
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)  
public class EmailService {}

Alternatively you can define the LoginController as prototype as well.

like image 94
db80 Avatar answered Oct 21 '25 16:10

db80