@Qualifier & @Autowired对象为空。

问题描述 投票:0回答:1

我有下面的代码。

@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 变成了null。知道为什么会这样吗?

谅谅

spring-boot java-8 spring-annotations
1个回答
0
投票

可能你会漏掉对流式层次结构中任何类的注释。

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

IoC就像块上的酷孩子,如果你使用Spring,那么你需要一直使用它。

所以要确保你在整个流程中没有任何对象是用new operator创建的。

@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 );
}

这将在服务类中抛出一个NullPointerException,当它试图访问MyRepository自动布线的Repository时,不是因为Repository的布线有什么问题,而是因为你用MyService my = new MyService()手动实例化了MyService()。

更多细节,你可以查看https:/www.moreofless.co.ukspring-mvc-java-autowired-component-null-repository-service

© www.soinside.com 2019 - 2024. All rights reserved.