-1

Lets say that I have a model for an object X, this object implements all the CRUD operations with the help of Spring Boot.

Now, I need to be able to edit this object using an standard POJO. The POJO looks like this:

public class Foo {
    @Autowired
    private XRepository xDAO;
    /*
      Do whatever I want with X and then save it again in the DB using xDAO
    */
}

So far I've tried using @Configurable, @Component and even @Service, but neither of those can @Autowire my XRepository.

What can I do?

Alberto Alegria
  • 1,023
  • 10
  • 26

2 Answers2

0

What you describe is not possible. Components can be wired only if the object is managed by Spring. In your case it's not and as such it's not possible to autowire in any dependency. You have various options. Here are some:

  1. Use repository outside of Foo class. Orchestrate the operations in another class that is managed by Spring
  2. Pass repository as dependency to Foo in the constructor by class that is managed by Spring
  3. This is somewhat hacky and probably not recommended but you can make repository a static variable in Foo and set it up by Spring managed component in something like @PostConstruct

In my opinion the best is to use option 1.

dev4Fun
  • 990
  • 9
  • 18
-1

I think that I didn't express myself sufficiently, either way I found a solution to my problem.

The solution is here.

I only declared Foo as a @Service, then I just @Autowired Foo:

@Autowired
public class Foo {
@Autowired
    private XRepository xDAO;
    //some code
}

Then I call this class using the @Autowired annotation

@Autowired Foo foo
foo.doThings();
Community
  • 1
  • 1
Alberto Alegria
  • 1,023
  • 10
  • 26