Potrzebuję pomocy w zrozumieniu pojęcia stojącego za @Autowired
i @Service
. Mam DAO zdefiniowany z @Service
i kontroler z @Autowired
i wszystko wydaje się w porządku, jednak używam tego samego @Autowired
w innej klasie, to nie działa.@Autowired i @Service działa z kontrolera, ale nie z innego pakietu.
Przykład:
usługi
@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";
}
}
Powyższy wszystko działa poprawnie. Jednakże, jeśli chcę użyć MyService
w POJO, to po prostu nie działa. Przykład:
package com.springtest.mywork.pojos;
public class MyPojo {
@Autowired
MyService myService;
public void testFromPojo() {
myService.someDataAccessMethod(); //myService is still null
}
}
Wiosna Config:
<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>
jest 'MyPojo' wystąpienia do wiosny? –
Nic nie zrobiłem dla 'MyController' w pliku config.xml, więc nie zrobiłem tego również dla' MyPojo'. Co powinienem robić? – birdy
Czy możesz opublikować konfigurację Spring? –