gpt4 book ai didi

java - @Service 和 @Scope ("prototype") 一起

转载 作者:行者123 更新时间:2023-11-30 06:14:16 26 4
gpt4 key购买 nike

我有一个带有 @Service 和 @Scope("protoype") 的服务类。我希望该服务的行为类似于 Controller 类中的原型(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 定义为原型(prototype)。

关于java - @Service 和 @Scope ("prototype") 一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49575345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com