Ich brauche Hilfe, das Konzept hinter @Autowired
und @Service
zu verstehen. Ich habe ein DAO mit @Service
und Controller mit @Autowired
definiert und alles scheint in Ordnung, aber ich benutze das gleiche @Autowired
in einer anderen Klasse, dann funktioniert es nicht.@Autowired und @Service arbeiten von Controller, aber nicht aus einem anderen Paket
Beispiel:
Dienst
@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";
}
}
Die vor allem gut funktioniert. Wenn ich jedoch MyService
in einem POJO verwenden möchte, dann funktioniert es einfach nicht. Beispiel:
package com.springtest.mywork.pojos;
public class MyPojo {
@Autowired
MyService myService;
public void testFromPojo() {
myService.someDataAccessMethod(); //myService is still null
}
}
Frühling 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>
Ist 'MyPojo' von Spring instanziiert? –
Ich habe nichts für 'MyController' in config.xml getan, also habe ich es auch nicht für' MyPojo' gemacht. Was soll ich tun? – birdy
Können Sie Ihre Spring-Konfiguration posten? –