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

标签 java spring spring-boot annotations

这是我的课,

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)

如何实现这样的目标?

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

  1. 构造函数 Autowiring 。
  2. 使用@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/

相关文章:

java - 使用 for 循环修复 switch 语句的返回值

java - 如何处理异常

java - 如何在单击按钮时关闭小程序

java - Spring 集成网关 - BeanCreationException

java - 带进度条的通知无法展开(Nougat+)

java - Spring 数据JPA : Invalid object name if use more than one Config Class in jUnit test

java - 如何在 Spring 事务中获取连接?

spring - logback找不到maven的属性project.build.directory

spring - 在IDE中运行Spring Boot时找不到JSP,但手动运行时可以工作

spring-boot - 在 spring boot 中启用 Redis 缓存