提问人:J.J. Beam 提问时间:10/11/2023 更新时间:10/11/2023 访问量:72
我可以创建异常作为 spring bean 吗?[已结束]
Can I create an exception as a spring bean? [closed]
问:
我可以创建一个 Java 异常的 spring bean 吗?
然后多次抛出它(比如说通过 setter 使用不同的字符串)
答:
-1赞
Partha Sai
10/11/2023
#1
是的,我们可以创造。示例代码如下。
@Configuration
public class AppConfig {
@Bean
public MyCustomException myCustomException() {
return new MyCustomException("This is a Spring-managed exception.");
}
}
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
}
对于自定义异常,如下所示:
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
public void setCustomMessage(String message) {
// This is a bit hacky, but demonstrates the concept
this.setStackTrace(this.getStackTrace());
this.initCause(null);
this.suppressedExceptions.clear();
super.fillInStackTrace();
try {
Field detailMessage = Throwable.class.getDeclaredField("detailMessage");
detailMessage.setAccessible(true);
detailMessage.set(this, message);
} catch (Exception e) {
throw new RuntimeException("Failed to set custom message.", e);
}
}
}
@Configuration
public class AppConfig {
@Bean
public MyCustomException myCustomException() {
return new MyCustomException("Initial message.");
}
}
@Service
public class SomeService {
@Autowired
private MyCustomException myCustomException;
public void someMethod() {
myCustomException.setCustomMessage("New message.");
throw myCustomException;
}
}
评论
5赞
f1sh
10/11/2023
这不是一个好建议,甚至不是一个好主意。这根本不是线程安全的。它带来的问题比重用同一实例的好处要多得多。
评论