Can we use @autowired on an entity object in spring?

Viewed 9864

I have a entity class called Customer, I am using this entity object in another class to set the data. When I use this object below like

@Autowired
Customer customer

Spring is complaining that please configure the bean in your classes.

Can we use auto wiring with entity objects?

4 Answers

You can only autowire only those beans whose life-cycle are managed by Spring IoC container.

These beans are defined in xml form with </bean> tag, or with some special annotations like @Bean, @Component, @Service, @Repository etc.

On the other hand,

in simple terms, entities are some java objects that you will need to create, update by yourself according to your business logic and save/update/remove them in/from DB. Their life-cycle cannot be managed by Spring IoC container.

So, you should never feel like you need to autowire an entity if you are doing it right!

In fact, Spring support @Autowire only for Spring Beans. A java class becomes Spring Bean only when it is created by Spring, otherwise it is not.

A workaround might be to annotate your class with @Configurable but you would have to use AspectJ

Please look in the Spring documentations on how to use @Configurable

Also, I wonder why you would autowire an entity class ?

I would warn you not to mix Spring Bean and JPA entities in one class/usecase because:

  • Spring Beans are instantiated and managed by Spring
  • Entities are managed by JPA provider

If you mean JPAs @Entity-annotation, Spring is simply telling you, that there isn't a bean in its context. On startup/runtime classes in the application will be scanned and each class annotated with spring annotations like @Component, @Service etc. will be instantiated as beans and put into a global context (Spring applicationcontext). This context is then used to lookup and inject those beans into other beans when @Autowired is found during scanning.

Opposed to this, @Entity is used during the creation of the Persistence-Context of JPA (as far as I remember) which isn't aware of Spring and it's context.

Most of the solutions to make both contexts aware of each other a mostly a little bit hacky.

Related