【问题标题】:Autowire giving null object in spring boot utility classAutowire 在 Spring Boot 实用程序类中给出空对象
【发布时间】:2016-12-10 01:23:28
【问题描述】:

我正在尝试使用自定义方言在 thymeleaf 页面上显示来自数据库的一些信息,但是在实用程序类中,我将自动装配的存储库设为空。

这是我的百里香代码

这是实用类

@Autowired(必需=真) 私有用户存储库用户存储库;

public String getUserFullName(String useUsername){

    String fullname = "";

    if(useUsername != null && useUsername.length() > 0){
        User user = userRepository.findByUseUsername(useUsername);
        if(user != null){

            String profession = user.getUseProfession();
            if(profession == null || profession.length() < 1) {
                fullname = fullname + user.getUseSurname() + ", " + user.getUseFirstname();
            }
            else {
                fullname = fullname + user.getUseSurname() + ", " + user.getUseFirstname() + " (" + profession + ")";
            }
        }
    }
    return fullname;
}

我正在像这样在方言中添加实用程序类

  @Override
  public Map<String, Object> getAdditionalExpressionObjects(IProcessingContext ctx) {
    Map<String, Object> expressions = new HashMap<>();
    expressions.put("fullnameUtil", new FullNameUtil());
    return expressions;
  }

我将 userRepository 设为 null。

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    通过在自定义方言中自动装配实用程序类解决了问题

    @Autowired(必需=真) 私有 FullNameUtil fullNameUtil;

      @Override
      public Map<String, Object> getAdditionalExpressionObjects(IProcessingContext ctx) {
        Map<String, Object> expressions = new HashMap<>();
        expressions.put("fullnameUtil", fullNameUtil);
        return expressions;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多