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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With