0

Can i make my repository be accessed in a class who isn't a RestController or something like that ?

I have an WatchService who listen a folder, to reads the files and after persist to a database. My watchservice works just like reading files, but I want persist using my JPARepository to persists, can i do that?

Springboot Application v2.1.6.RELEASE

@Repository
public interface MyRepository extends JpaRepository<MyClass, Long> { }

public class MyWatchService implements Runnable{

@Autowired
private MyRepository myRepository;

// SOME CODES COMES HERE 

@Override
public void run() {     
// SOME CODES COMES HERE 
myRepository.save(MyClass); // In this point give a nullPointerException
}

}

I get that Exception:

java.lang.NullPointerException
at com.WatchService.run(WatchService.java:515)
at java.base/java.lang.Thread.run(Thread.java:835)

1 Answers1

0

You get the NullPointerException because the dependency did not get injected. You used the annotation correctly, but the dependencies do not get injected, by some magic.

In order for this to work (i.e. for the beans to get injected), you need to let the DI- or IoC Container instantiate the bean for your (in JEE this would be CDI, in Spring it is the Spring IoC Container). This can be done by injection (d'uh! Injection-inception) or programmatically.

A Spring-centric solution is explored in this question.

Turing85
  • 18,217
  • 7
  • 33
  • 58
  • But i need to explicitly intantiate my Class, cause it is a Thread `Thread thread = new Thread(MyWatchService); thread.start();` – Fabricio Carvalho Aug 22 '19 at 19:44
  • You can either retrieve the bean instance for `MyRepository` as it is explained in the question I linked or you have to do the injection yourself, which could be hard if you use other resoruces like database connections,.... – Turing85 Aug 22 '19 at 19:48