0

I have interface like this

@Repository
public interface CarRepository extends JpaRepository<Car, Long> {
}

In class adnotated @RestController Spring is able to wired with proper field.

But how can I do this if I want to create class without any adnotation in spring? I have to create implementation of this repository? If yes, can I do it like spring is?

  • Possible duplicate of [How to inject dependencies into a self-instantiated object in Spring?](https://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring) – Lesiak Apr 20 '19 at 13:18
  • why you need that for? unit testing? – Maciej Kowalski Apr 20 '19 at 13:36

2 Answers2

0

Inject

private final ConfigurableApplicationContext configurableApplicationContext;

into the class instantiating your desired class. Then call:

YourClass yourClass = (YourClass) configurableApplicationContext.getBeanFactory().initializeBean(new YourClass(), "YourClassName");

yourClass will then hold an instance of YourClass which has been initialized as if it was a Spring @Component (or a @RestController, which is the same from the dependency-injection point of view).

Alex B
  • 354
  • 1
  • 9
-1
@SpringBootApplication
public class MainApplication  extends SpringBootServletInitializer implements ApplicationContextAware {

    private static ApplicationContext appContext;

    public static void main(String[] args) {
        SpringApplication.run(CrawlerApplication.class, args);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.appContext = applicationContext;
    }

....

MainApplication.getAppContext().getBean(CarRepository.class)