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

标签 java spring-mvc spring-boot

我有一个带有 @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/

相关文章:

java - 在 org.elasticsearch.client.RestHighLevelClient 中获取没有 id 的结果

spring-boot - 如何更改<主机 :port> to domain in swagger

java - JScrollPane 格式化以显示 Pascals 三角形

java - 是否可以在一个 spring 容器中运行带有 spring security 的 spring webmvc webapp?

java - Spring框架: Register conversion-service with java config

java - 如何获取默认的 WebApplicationContext?

java - 有没有一种简单的方法可以从 Maven POM 生成 Ant 构建脚本?

java - 如何避免 instanceof 调用?

java - Spring MVC 中的数据表

java - Spring 启动: @Autowired remember and save the same object also for the next request