我在自動裝配和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