问题描述
一般来说,我在使用自动接线和DI时遇到问题,所以我希望有人可以帮助我,因为我已经被困了好几天了.
I'm having some problem with autowire and DI in general, so I hope that someone can help cause I've been stuck for days now.
这是代码:
@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中,我得到了:
In my beans.xml I've got:
<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时失败.
Can someone please help out with this? What am I doing wrong? It seems that autowiring is working all until the next step where it fails when injecting dataSource.
编辑:我在玩代码,在setDataSource()之前忘记了@Autowire,但应该在那儿了.
EDIT: I was playing with the code, and forgot @Autowire before setDataSource() but it is supposed to be there.
推荐答案
也许您缺少接线配置,请尝试
Maybe you're missing wiring configuration, try
<context:annotation-config/>
这篇关于Spring-如何自动连接数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!