@Service and @Scope(“prototype”) together

天涯浪子 提交于 2020-05-29 14:28:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49575345/service-and-scopeprototype-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!