AntonBoarf
AntonBoarf

Reputation: 1313

Spring : creating beans with @Bean

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 ?

Upvotes: 0

Views: 753

Answers (3)

knittl
knittl

Reputation: 265221

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.

Upvotes: 1

GJohannes
GJohannes

Reputation: 1763

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();
    }
} 

Upvotes: 1

Rahul Gupta
Rahul Gupta

Reputation: 29

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

Upvotes: 1

Related Questions