@Service 和 @Scope("prototype") 在一起

2024-01-10

我有一个带有 @Service 和 @Scope("prototype") 的服务类。我希望该服务的行为类似于控制器类中的原型。我的使用方法如下:

@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();
}

这是服务类别:

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

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

我使用自动配置属性运行 spring boot。我比较“emailService”对象是否相同,并且得到相同的结果 一个物体。这意味着 @Scope("prototype") 不能按预期与 @Service 一起工作。你看到这里有什么问题吗?我是否忘记添加一些代码?

编辑: 回复@Janar,我不想使用额外的代码来使其工作,例如 WebApplicationContext 属性和额外的创建方法。我知道有一种更短的方法,仅使用注释。


您必须在中指定代理模式scope注解。

这应该可以解决问题:

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

或者,您可以定义LoginController作为原型也是如此。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@Service 和 @Scope("prototype") 在一起 的相关文章

随机推荐