簡體   English   中英

Spring MVC測試,JNDI

[英]Spring MVC testing, JNDI

我想將現有數據源綁定到我的測試的JNDI名稱。

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml",
        "file:WebContent/WEB-INF/test-datasource.xml" })
public class SimulatorTest {

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @PostConstruct
    public void createContext() throws NamingException {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        builder.bind("java:comp/env/jdbc/DefaultDB", dataSource);
        builder.activate();
    }
...

這似乎可行,但是只要我的代碼(即EclipseLink)嘗試查找此JNDI名稱,它就會失敗:

Exception Description: Cannot acquire data source [java:comp/env/jdbc/DefaultDB].
Internal Exception: javax.naming.OperationNotSupportedException: SimpleNamingContext does not support [javax.naming.Name]

我看過源代碼,但實際上並沒有: https : //github.com/spring-projects/spring-framework/blob/master/spring-test/src/main/java/org/springframework/mock /jndi/SimpleNamingContext.java#L225-L293

如何創建上下文,以使EclipseLink不會查找數據源?

解決了我的問題。 只是避免在測試期間使用JNDI,至少這也是很多人建議的。

在我的代碼中,我手動創建了一個EntityManagerFactory ,它查找在persistence.xml中定義的JNDI字符串。 由於缺少JNDI,在測試期間此操作失敗。

現在,讓Spring為我創建EntityManagerFactory並讓Spring選擇數據源。

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="MyPU" />
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
    </property>
    <property name="jpaPropertyMap">
        <props>
            <prop key="eclipselink.logging.level">INFO</prop>
            <prop key="eclipselink.weaving">false</prop>
        </props>
    </property>
</bean>

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/DefaultDB" expected-type="javax.sql.DataSource" />

不在persistence.xml而是在spring配置中定義數據源的JNDI名稱的好處是,Spring可以在測試期間覆蓋dataSource因此,現在進行JNDI查找,沒有失敗的測試。

暫無
暫無

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

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