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

后端 未结 4 995
别跟我提以往
别跟我提以往 2021-01-22 01:18

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
         


        
相关标签:
4条回答
  • 2021-01-22 01:40

    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
    0 讨论(0)
  • 2021-01-22 01:44

    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 ?

    0 讨论(0)
  • 2021-01-22 01:50

    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!

    0 讨论(0)
  • 2021-01-22 01:55

    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.

    0 讨论(0)
提交回复
热议问题