如何在构造函数中使用@Autowired bean?

Sub*_*lil 2 java spring annotations spring-boot

这是我的课,

public class MyBusinessException extends RuntimeException {
    @Autowired
    private MessageSource messageSource;

    private String errorCode;

    private String messageInEnglish;

    public MyBusinessException(String errorCode){
       this.errorCode=errorCode;
       this.messageInEnglish=messageSource.getMessage(this.code,null, Locale.ENGLISH);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个异常类。当我将它errorCode作为参数传递给构造函数时,它应该填充错误消息,这就是我要寻找的。事实上,我想像这样实例化类

throw new MyBusinessException("MY-ERROR-CODE");//want to initiate like this(only one argument for constructor)
Run Code Online (Sandbox Code Playgroud)

如何实现这样的目标?

到目前为止,我已经尝试了所有这些:

  1. 构造函数自动装配。
  2. 使用 @PostConstruct

dav*_*xxx 5

throw new MyBusinessException("MY-ERROR-CODE");//想这样启动(构造函数只有一个参数)

您不能@Autowired与不是由 Spring 创建的对象一起使用。
我认为您应该重构代码以向 MyBusinessException 构造函数提供所需的所有信息。
您不需要将其与 Spring 结合使用。

依赖于 Spring 的逻辑:

@Autowired
private MessageSource messageSource; 
...
messageSource.getMessage(this.code,null, Locale.ENGLISH);
Run Code Online (Sandbox Code Playgroud)

可以移动到将创建完全初始化MyBusinessException实例的 Spring bean 。
此外,messageSource.getMessage(this.code,null, Locale.ENGLISH)可能需要其他例外情况。在特定的类中移动这个逻辑是有道理的。

@Bean
public class ExceptionFactory{
   @Autowired
   private MessageSource messageSource; 

   public MyBusinessException createMyBusinessException(String errorCode){        
      return new MyBusinessException(errorCode, messageSource.getMessage(this.code,null, Locale.ENGLISH));        
  } 
}
Run Code Online (Sandbox Code Playgroud)

您可以注意到,createMyBusinessException()它为客户端提供了一个简单的 API:他们只需要传递错误代码String即可创建异常。
MessageSource相关性是一个实现细节,他们并不需要费心。

例如,这就足够了:

throw exceptionFactory.createMyBusinessException("MY-ERROR-CODE");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你。在您的代码中,查找消息的语句也只执行一次:在`MyBusinessException` 构造函数中。当前解决方案的优点在于: 1) 关注点分离:其他异常可能需要`messageSource.getMessage(this.code,null, Locale.ENGLISH)`。在特定的类中移动这个逻辑是有道理的。2)客户端的简化API:您不需要每次都传递两个参数来创建异常。只需错误代码字符串就足够了。 (2认同)