java spring - 如何自动装配数据源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12786754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:13:18  来源:igfitidea点击:

spring - how to autowire data source?

javaspringdatasourcedaoautowired

提问by newman555p

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.

总的来说,我在自动装配和 DI 方面遇到了一些问题,所以我希望有人能帮助我,因为我已经被困了好几天了。

This is the code:

这是代码:

@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");
}
...
}

In my beans.xml I've got:

在我的 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" />

This doesn't work and I get:

这不起作用,我得到:

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.` 

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.

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

EDIT: I was playing with the code, and forgot @Autowire before setDataSource() but it is supposed to be there.

编辑:我在玩代码,在 setDataSource() 之前忘记了@Autowire,但它应该在那里。

回答by Rrr

Maybe you're missing wiring configuration, try

也许您缺少接线配置,请尝试

<context:annotation-config/>

<context:annotation-config/>

回答by venkat

This will be due to the order of bean instance creation. Your DAO has been instantiated before the dataSource instance created.

这将取决于 bean 实例创建的顺序。在创建 dataSource 实例之前,您的 DAO 已被实例化。

Keep your data Source bean definition before

保留您的数据源 bean 定义之前

other way is , define your dataSource definitions in a separate xml and import that before

另一种方法是,在单独的 xml 中定义您的数据源定义并在此之前导入

回答by quartzde

Looks like you are using Spring 2.0but i think context:component-scanwas introduced in Spring 2.5. Maybe update spring xml-config and spring dependencies to 2.5?

看起来您正在使用,Spring 2.0但我认为context:component-scan是在Spring 2.5. 也许将 spring xml-config 和 spring 依赖项更新为2.5

回答by pap

Change

改变

<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>

to

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" 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>

The property is called driverClassName, not driverClass.

该属性称为driverClassName,而不是driverClass

Also, you don't need multiple context:component-scanelements You can change

此外,您不需要多个context:component-scan元素您可以更改

<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" />

To

<context:component-scan base-package="bp.dao,bp.mvc,bp.svc,bp.view" />

回答by Anshu

Try org.apache.commons.dbcp.BasicDataSource:

尝试org.apache.commons.dbcp.BasicDataSource

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://127.0.0.1:3306/mytckdb?autoReconnect=true"
        p:username="user" p:password="pass" />

I use JPA so generally prefer to create EntityManagerFactory and use that

我使用 JPA,所以通常更喜欢创建 EntityManagerFactory 并使用它

    <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="persistenceUnitName" value="PU" />
            <property name="jpaVendorAdapter">
                <bean id="jpaAdapter"
                    class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="database" value="${database}" />
                    <property name="showSql" value="true" />
                    <property name="generateDdl" value="false" />
                </bean>
            </property>
        </bean>

<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="txManager" />