I need help understanding the concepts of @Autowired and @Service . I have a DAO defined using @Service and a controller with @Autowired and everything seems fine, however I use the same @Autowired in a different class, then it does not work.
Example:
Service
@Service public class MyService { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource (DataSource myDataSource) { this.jdbcTemplate = new JdbcTemplate(myDataSource); } public void testUpdate(){ jdbcTemplate.update("some query"); } }
controller
package com.springtest.mywork.controller; @Controller @RequestMapping(value = "/test.html") public class MyController { @Autowired MyService myService; @RequestMapping(method = RequestMethod.GET) public String test(Model model) { systemsService.testUpdate(); return "view/test"; } }
Above everything works fine. However, if I want to use MyService in POJO, then it just does not work. Example:
package com.springtest.mywork.pojos; public class MyPojo { @Autowired MyService myService; public void testFromPojo () { myService.someDataAccessMethod();
Spring Configuration:
<beans> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <context:component-scan base-package="com.springtest.mywork" /> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb" /> <property name="username" value="hello" /> <property name="password" value="what" /> </bean> <bean name="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate"> <constructor-arg ref="dataSource"/> </bean> </beans>
birdy source share