I need help understanding the concept behind @Autowired
and @Service
. I have a DAO defined with @Service
and controller with @Autowi
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.
check your context component scan in your configuration file
<context:component-scan base-package="<your_package>" />
Include this in applicationContext.xml file
<context:annotation-config />
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
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?