-1

I am having following code below.

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

and FindEmpByDepartment class below.

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

}
    ....
    }

My problem is I am always getting null when invoke

this.empByDepartment.getList();

line. Here this.empByDepartment is coming as null. Any idea why it is like this?

Thanks

AnKr
  • 433
  • 1
  • 6
  • 20
  • `@Autowired` only works in Spring beans (objects created and managed by the Spring application context). It does not work in arbitrary objects created with `new` or by a builder. Your class `Employee` doesn't look like it's a Spring bean. See: [Why is my Spring `@Autowired` field `null`?](https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – Jesper May 19 '20 at 13:28

1 Answers1

0

May be you would have missed annotating any class in the flow hierarchy .

@Service, @Repository and @Controller are all specializations of @Component, so any class you want to auto-wire needs to be annotated with one of them.

IoC is like the cool kid on the block and if you are using Spring then you need to be using it all the time .

So make sure you do not have any object created with new operator in the entire flow .

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

This will throw a NullPointerException in the service class when it tries to access the MyRepository auto-wired Repository, not because there is anything wrong with the wiring of the Repository but because you instantiated MyService() manually with MyService my = new MyService().

For more details , you can check https://www.moreofless.co.uk/spring-mvc-java-autowired-component-null-repository-service/