Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot @限定符及@自动连线对象为空_Spring Boot_Java 8_Spring Annotations - Fatal编程技术网

Spring boot @限定符及@自动连线对象为空

Spring boot @限定符及@自动连线对象为空,spring-boot,java-8,spring-annotations,Spring Boot,Java 8,Spring Annotations,我有下面的代码 @Builder(toBuilder = true) @AllArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE) @ToString @EqualsAndHashCode @Configurable public class Employee { @Autowired @Qualifier("findEmpByDepartment") pri

我有下面的代码

@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();
}
}
@Builder(toBuilder=true)
@AllArgsConstructor(access=AccessLevel.PRIVATE)
@NoArgsConstructor(access=AccessLevel.PRIVATE)
@托斯特林
@EqualsAndHashCode
@可配置
公营雇员{
@自动连线
@限定词(“FindDempByDepartment”)
私人职能部门;
私有void save(){
this.empByDepartment.getList();
}
}
查找下面的部门

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

}
    ....
    }
@组件(“findEmpByDepartment”)
公共类FindEmpByDepartment实现函数{
public void getList(){
}
....
}
我的问题是调用时我总是得到null

this.empByDepartment.getList()

线路。此处此.empByDepartment为空。知道为什么会这样吗


谢谢

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

@服务、@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 );
}
@控制器
公共类控制器{
@GetMapping(“/example”)
公共字符串示例(){
MyService my=新的MyService();
我的.doStuff();
}
}
@服务
公共类MyService(){
@自动连线
MyRepo;
公共空间{
回购findByName(“史蒂夫”);
}
}
@存储库
公共接口MyRepository扩展了Crudepository{
列出findByName(字符串名称);
}
这将在服务类尝试访问MyRepository自动连接存储库时在服务类中引发NullPointerException,这不是因为存储库的连接有任何问题,而是因为您使用MyService my=new MyService()手动实例化了MyService()

有关更多详细信息,请查看

@Autowired
仅适用于Springbeans(由Spring应用程序上下文创建和管理的对象)。它不适用于使用
new
或生成器创建的任意对象。您的类
Employee
看起来不像是Springbean。见: