Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to instantiate spring data jpa repository without autowired

I have my repository interface as

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;


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

and the service impl file in where I want to use above repository is not a @Component or @Service because its object is created using new. So it is not allowing autowiring or injecting the repository in my service impl class.

Is there any other way around to implement in such case?

like image 744
Navdeep Singh Avatar asked Jul 30 '18 13:07

Navdeep Singh


1 Answers

There are a couple of options available.

First of all, you can use it as a normal dependency and use a factory bean to instantiate your object.

@Component
public class MyFactoryBean {

    private Repository repository;

    @Autowired
    public MyFactoryBean(Repository repository) {
        this.repository = repository;
    }

    public Instance getInstance(Parameter parameter) {
        return new Instance(repository, parameter);
    }
}

If your parameter does not change at runtime, you can provide a bean in your configuration:

@Configuration
public class MyConfiguration {

    private Repository repository;

    @Autowired
    public MyConfiguration(Repository repository) {
        this.repository = repository;
    }

    @Bean 
    public Instance instance(){
        Parameter parameter = ... // value in a config file or static value 
        return new Instance(repository, parameter);
    }
}

Also, you can use the AutowireCapableBeanFactory to inject dependencies as normal for objects not managed by Spring. Remember that you need to use setter injection tough.

private AutowireCapableBeanFactory beanFactory;

@Autowired
public MyFactoryBean(AutowireCapableBeanFactory beanFactory) {
    this.beanFactory = beanFactory;
}

public void doStuff() {
    MyService service = new MyService();
    beanFactory.autowireBean(service); // dependencies will be autowired
}
like image 185
Glains Avatar answered Nov 16 '22 17:11

Glains