我在春天比较新,我在理解春天mvc的基本原理方面遇到了问题。
我的控制器
@Controller
public class HomeController {
private ContactManager contactManager;
@Autowired
public void setContactManager(ContactManager contactManager) {
this.contactManager = contactManager;
}
@RequestMapping(value="/")
public ModelAndView listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactManager.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
...
联系ManagerImpl,并实现接口方法
public class ContactManagerImpl implements ContactManager {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
...
的ContactManager
public interface ContactManager {
public void saveOrUpdate(Contact contact);
public void delete(int contactId);
public Contact get(int contactId);
public List<Contact> list();
}
和root-context.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="sec"/>
</bean>
<bean id="managmentService" class="spring.contact.impl.model.ContactManagerImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
我的问题是我收到错误:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of
type [spring.contact.api.ContactManager] found for dependency: expected at least 1
bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
当然问题在于@Autowired注释。我该如何解决?当我删除@Autowired注释时,我得到另一个错误:NullPointerException(HomeController中的管理器)。
答案 0 :(得分:0)
您的控制器应该是..
@Controller
public class HomeController {
@Autowired
@Qualifier("managmentService")
private ContactManager contactManager;
@RequestMapping(value="/")
public ModelAndView listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactManager.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
...
在您的配置中,还添加<context:annotation-config />
,以便能够使用@Autowired注释。
<context:annotation-config />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
答案 1 :(得分:-1)
将@Autowired注释移动到ContactManager的声明。
你不需要设置者,删除它。