@Autowired and @Service working from controller but not from a different package

后端 未结 5 809
栀梦
栀梦 2021-02-08 14:54

I need help understanding the concept behind @Autowired and @Service. I have a DAO defined with @Service and controller with @Autowi

相关标签:
5条回答
  • 2021-02-08 15:39

    When using classpath scanning, you have to communicate to Spring which classes to manage. This is done using the @Service annotation, and its relations (@Controller, @Repository, etc).

    If you choose not to annotate your bean, you must explicitly declare it in your config, just like you did with dataSource and jdbcTemplate.

    Annotating your classes means only those classes in the package are managed by Spring; which allows you to scan a package without having to manage all classes in that package.

    0 讨论(0)
  • 2021-02-08 15:39

    check your context component scan in your configuration file

    <context:component-scan base-package="<your_package>" />
    
    0 讨论(0)
  • 2021-02-08 15:41

    Include this in applicationContext.xml file

    <context:annotation-config />
    
    0 讨论(0)
  • 2021-02-08 15:42

    You can implement this to use spring-managed beans in your POJO class.

    http://www.javacodegeeks.com/2015/03/using-spring-managed-bean-in-non-managed-object.html

    0 讨论(0)
  • 2021-02-08 15:56

    It is because your POJO class is not managed by spring container.

    @Autowire annotation will work only those objects which are managed by spring (ie created by the spring container).

    In your case the service and controller object are managed by spring, but your POJO class is not managed by spring, that is why the @Autowire is not producing the behavior expected by you.

    Another problem I noticed is, you are using the @Service annotation in the DAO layer when spring has the @Repository annotation specifically created for this purpose.

    Also it is not desirable to allow spring to manage the POJO classes since normally it will be data storage elements which has to be created outside the container.

    Can you tell us what is the purpose of the POJO class and why the service instance is used in it?

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