我在自动装配和DI方面遇到了一些问题,所以我希望有人可以帮忙,因为我现在已经坚持了几天。春天 - 如何autowire数据源?
这是代码:
@Service
public class TicketsController implements Controller {
private TicketManager ticketManager;
@Autowired
public void setTicketManager(TicketManager ticketManager) {
this.ticketManager = ticketManager;
}
...
}
@Service
public class SimpleTicketManager implements TicketManager {
private TicketsDao ticketsDao;
@Autowired
public void setTicketsDao(TicketsDao ticketsDao) {
this.ticketsDao = ticketsDao;
}
...
}
@Repository
public class JdbcTicketDao implements TicketsDao {
private DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource=dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
...
}
public final class AppContext {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
BeanFactory factory = context;
TicketsController ticketsController = (TicketsController) factory.getBean("ticketsController");
}
...
}
在我的beans.xml我有:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mytckdb"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<context:component-scan base-package="bp.dao" />
<context:component-scan base-package="bp.mvc" />
<context:component-scan base-package="bp.svc" />
<context:component-scan base-package="bp.view" />
这不工作,我得到:
Error creating bean with name 'jdbcTicketDao': Injection of autowired dependencies failed
... nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [javax.sql.DataSource] found for dependency.`
灿有人请帮忙吗?我究竟做错了什么?看起来,自动装配工作直到下一步注入dataSource时失败。
编辑:我在玩代码,并忘记setDataSource()之前的@Autowire,但它应该在那里。
错误消息似乎表明你想'@ Autowire'但显示的代码表示相反。你能澄清一下吗? – 2012-10-08 17:48:58
对不起,忘了在setDataSource之前添加@Autowired,但它在那里,我有同样的问题。 – newman555p
我疯狂的猜测是'beans.xml'在Spring中没有被看作applicationContext。如果你可以提供更多关于你如何“启动”的细节spring – 2012-10-08 17:54:02