java-spring-如何自动连接数据源?

前端之家收集整理的这篇文章主要介绍了java-spring-如何自动连接数据源? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我通常在自动接线和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.` 

有人可以帮忙吗?我究竟做错了什么?似乎自动装配可以一直工作到下一个步骤,该步骤在注入dataSource时失败.

编辑:我在玩代码,并在setDataSource()之前忘了@Autowire,但应该在那儿.

最佳答案
也许您缺少接线配置,请尝试

< context:annotation-config />

猜你在找的Spring相关文章