簡體   English   中英

Spring - 在xml-config中注入JpaRepository而不使用自動裝配

[英]Spring - inject JpaRepository in xml-config without using autowiring

我目前正在開始一個將spring-data與JPA / Hibernate結合使用的項目。 現在,我正在使用相關屬性上的@Autowired注釋注入JpaRepositories,例如:

@Component
public class EmployeeGenerator implements IDataGenerator {
...
    @Autowired
    private IEmployeeDao        dao;
...
}

..其中IEmployeeDao是一個擴展JpaRepository的接口,注釋為@Repository:

@Repository
public interface IEmployeeDao extends JpaRepository<Employee, Integer> {

     /**
     * Finds employees by username.
     *
     * @param username the username
     * @return the list of employees
     */
    List<Employee> findByUsername(String username);

使用這種方法一切正常 - 但是,我習慣於用XML完成大部分彈簧配置工作,因為我個人喜歡將所有相關配置放在同一個地方並且第一眼就能看到的想法。

現在,據我了解JPA和spring-data,存儲庫實例以某種方式由JPA實體管理器創建,所以我應該能夠使用..某種工廠方法在spring config xml中將它們指定為bean? 我想我正在尋找以下內容:

<import resource="classpath:spring/db-context.xml"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="..."/>
    <property name="dataSource" ref="..."/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.connection.charSet">UTF-8</prop>
        </props>
    </property>
</bean>
...
<bean id="employeeDaoImpl" class="IEmployeeDao">
     <factory-method="?????"> <!-- Is something like this possible??? -->
</bean>

經過一些閱讀后,我想自動裝配存儲庫是“推薦”的方法,我確實看到了這樣做的一些好處,但仍然,出於興趣,我想讓它使用pure-xml配置(或者至少沒有@Autowired,那是)

您可以使用<jpa:repositories />聲明存儲<jpa:repositories /> 然后,您可以在XML配置中使用存儲庫引用。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <repositories base-package="com.acme.repositories" />

</beans:beans>

在這種情況下,我們指示Spring掃描com.acme.repositories及其所有子包,以用於擴展Repository或其子接口之一的接口。 對於發現的每個接口,它將注冊持久性技術特定的FactoryBean,以創建處理查詢方法調用的相應代理。 這些bean中的每一個都將在從接口名稱派生的bean名稱下注冊,因此UserRepository的接口將在userRepository下注冊。 base-package屬性允許使用通配符,以便您可以擁有掃描包的模式。

您可以在文檔中閱讀更多相關信息: http//docs.spring.io/spring-data/jpa/docs/1.3.0.RELEASE/reference/html/repositories.html#repositories.create-instances

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM