小编典典

@Service和@Scope(“ prototype”)一起

spring-mvc

我有一个@Service和@Scope(“ protoype”)服务类。我希望该服务的行为类似于控制器类中的原型。这是我的用法:

@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属性和创建的额外方法。我知道有一种仅使用注释的较短方法。


阅读 1425

收藏
2020-06-01

共1个答案

小编典典

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

这应该可以解决问题:

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

另外,您也可以将定义LoginController为原型。

2020-06-01