Home > Net >  Spring : creating beans with @Bean
Spring : creating beans with @Bean

Time:04-13

I have an issue with beans creations :

@Bean
Service carService() {
  return new Service(new CarRepository(), "car");
}

My issue is that CarRepository class has a dependency to EntityManager em variable (with @PersistenceContext)

So if I use new operator, I'm missing this dependency (because I'm instanciating myself the bean).

Also I have many services (CarService, BikeService etc...) and many repositories too (CarRepository, BikeRepository etc...). So using annotations directly in classes seems difficult.

So any solutions ?

CodePudding user response:

Simple. Pass your repository as dependency into your Bean factory function:

@Bean
Service carService(final CarRepository carRepository) {
  return new Service(carRepository, "car");
}

The repository needs to exist as a bean itself. You can create the repository bean in another bean method of a configuration class, or by annotating the class and having it created during component scanning.

CodePudding user response:

I think you need to annotate every repository class with @Repository annotation. And every service class with @Service.

CodePudding user response:

In Spring you should not use the new operator for Services. Use the annotation

@Service 
public classSomeClass {

or

@Component
public classSomeClass {

and your class can be injected via depnendency Injection. If you want to create a new custom bean that can be used via dependencyInjection This is what the @Configuration annotation is for.

@Configuration
public class ConfigurationClass{

    @Bean
    public SomeClass createSomeClass(){
      return new SomeClass();
    }
} 
  • Related