0

I have this Spring Data repository. Custom methods are auto-implemented by Spring Data (using reflection, proxies or whatever)

public interface UserRepository extends CrudRepository<User, String> {
    //custom methods
}

Somewhere, I have this:

@Autowired
UserRepository userRepository;

Now, I'm getting rid of Spring context and stop using Spring based dependency injection. I'm wonder if it's possible to create an instance of UserRepository without initialize the Spring context. Like this:

UserRepository userRepository = new UserRepository();

Obviously, that does not work. But I'm looking for something similar. According this answer, it's not possible to see the repository's generated code because Spring uses proxies runtime.

Is there a way to achieve what I want?

Héctor
  • 24,444
  • 35
  • 132
  • 243
  • 1
    It is possible, but will require tons of initializing code. – talex Feb 15 '19 at 10:12
  • Can I know how to start? – Héctor Feb 15 '19 at 10:25
  • Why are you stopping using Spring whilst you obviously still want to use it. Instead of `@Autowired` you can use the default `@Inject` or `@Resource` but underneath you still need the Spring container. However if you only want to use Spring Data JPA there is out-of-the-box support for using it in a CDI environment. – M. Deinum Feb 15 '19 at 10:27

1 Answers1

0

I found a solution. You need to use RepositoryFactorySupport class to create the repository.

In my case, I was using Elasticsearch and ElasticsearchRepository from Spring Data, so this works for me:

ElasticsearchRepositoryFactory factory = new ElasticsearchRepositoryFactory(jestTemplate);
MyRepo myRepo = factory.getRepository(MyRepo.class);
Héctor
  • 24,444
  • 35
  • 132
  • 243