这是我的课,
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);
}
}
这是一个异常类。当我将 errorCode
作为参数传递给构造函数时,它应该填充错误消息,这就是我正在寻找的。事实上,我想实例化类这个
throw new MyBusinessException("MY-ERROR-CODE");//want to initiate like this(only one argument for constructor)
如何实现这样的目标?
到目前为止我已经尝试过所有这些:
- 构造函数 Autowiring 。
- 使用
@PostConstruct
最佳答案
throw new MyBusinessException("MY-ERROR-CODE");//want to initiate like this(only one argument for constructor)
您不能对不是由 Spring 创建的对象使用 @Autowired
。
我认为您应该重构代码以向 MyBusinessException 构造函数提供所有需要的信息。
您不需要将其与 Spring 耦合。
依赖Spring的逻辑:
@Autowired
private MessageSource messageSource;
...
messageSource.getMessage(this.code,null, Locale.ENGLISH);
可以移动到将创建一个完全初始化的 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));
}
}
您可以注意到 createMyBusinessException()
为客户端提供了一个简单的 API:他们只需传递错误代码 String
即可创建异常。
MessageSource
依赖项是他们不需要理会的实现细节。
例如,这就足够了:
throw exceptionFactory.createMyBusinessException("MY-ERROR-CODE");
关于java - 如何在构造函数中使用@Autowired bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48501216/