一般来说,我在使用 autowire 和 DI 时遇到了一些问题,所以我希望有人能提供帮助,因为我已经被困了好几天了。
这是代码:
@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.`
有人可以帮忙吗?我究竟做错了什么?似乎自动装配一直有效,直到注入数据源时失败的下一步。
编辑:我在玩代码,在 setDataSource() 之前忘记了@Autowire,但它应该在那里。