首页 > 解决方案 > @Qualifier 和 @Autowired 对象为 null

问题描述

我在下面有以下代码。

@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@ToString
@EqualsAndHashCode
@Configurable
public class Employee {

@Autowired
@Qualifier("findEmpByDepartment")
private Function<Long, Long> empByDepartment;

private void save() {
   this.empByDepartment.getList();
}
}

和下面的FindEmpByDepartment类。

    @Component("findEmpByDepartment")
    public class FindEmpByDepartment implements Function<Long, Long> { 
public void getList() {

}
    ....
    }

我的问题是调用时我总是得到空值

this.empByDepartment.getList();

线。这里this.empByDepartment是空的。知道为什么会这样吗?

谢谢

标签: spring-bootjava-8spring-annotations

解决方案


您可能会错过注释流层次结构中的任何类。

@Service、@Repository 和 @Controller 都是 @Component 的特化,所以任何你想自动连接的类都需要用其中之一进行注解。

IoC 就像一个很酷的孩子,如果您使用 Spring,那么您需要一直使用它。

因此,请确保您在整个流程中没有使用 new 运算符创建任何对象。

@Controller
public class Controller {

  @GetMapping("/example")
  public String example() {
    MyService my = new MyService();
    my.doStuff();
  }
}

@Service
public class MyService() {

  @Autowired
  MyRepository repo;

  public void doStuff() {
    repo.findByName( "steve" );
  }
}



@Repository
public interface MyRepository extends CrudRepository<My, Long> {

  List<My> findByName( String name );
}

这将在服务类尝试访问 MyRepository 自动连接的存储库时引发 NullPointerException,这不是因为存储库的接线有任何问题,而是因为您使用 MyService my = new MyService() 手动实例化了 MyService()。

有关更多详细信息,您可以查看 https://www.moreofless.co.uk/spring-mvc-java-autowired-component-null-repository-service/


推荐阅读