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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With