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)
如何实现这样的目标?
到目前为止,我已经尝试了所有这些:
@PostConstructthrow 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)
| 归档时间: |
|
| 查看次数: |
1398 次 |
| 最近记录: |