簡體   English   中英

Spring @Autowired實例為null

[英]Spring @Autowired instance is null

我目前正在嘗試設置REST Service Spring應用程序,並實現了一個模型及其控制器+ dao和服務以與MySQL數據庫進行通信。

在此處輸入圖片說明

現在,我的AccountController是帶有注釋的@RestController的bean,而AccountService是@Component Bean。 AccountService擁有一個@ Autowire'd AccountDao成員,而AccountController擁有一個@ Autowire'd AccountService成員。

dataAccess.xml如下:

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

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/fashion" />
        <property name="username" value="root" />
        <property name="password" value="fashion" />
    </bean>

    <bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>de/appsiting/fashion/model/Account.hbm.xml</value>
           </list>
        </property>
        <property name="hibernateProperties">
           <props>
                <prop key="hibernate.dialect">
                org.hibernate.dialect.MySQL5Dialect
                </prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
           </props>
        </property>
    </bean>

    <bean id="jdbcExceptionTranslator" class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
       <property name="dataSource">
            <ref bean="dataSource" />
       </property>
    </bean>

    <bean id="accountDao" class="de.appsiting.fashion.persistence.AccountDao" />
</beans>

但是, Account.hbm.xml被塗成紅色,表明應用程序找不到它。 因此,我的第一個問題是,為什么不從resources文件夾中根目錄找到.hbm.xml?

如下所示填充serviceBeans.xml

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

    <task:annotation-driven/>

    <bean id="hibernateStringEncryptor" class="org.jasypt.hibernate4.encryptor.HibernatePBEStringEncryptor">
        <property name="registeredName">
            <value>strongHibernateStringEncryptor</value>
        </property>
        <property name="algorithm">
            <value>PBEWithMD5AndTripleDES</value>
        </property>
        <property name="password">
            <value>jasypt</value>
        </property>
    </bean>

    <bean id="accountService" class="de.appsiting.fashion.service.AccountService">
        <property name="accountDao" ref="accountDao" />
    </bean>

    <!-- *** TX LAYER -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:advice id="tx.advice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false" />
            <tx:method name="get*" propagation="REQUIRED" read-only="false" />
        </tx:attributes>
    </tx:advice>

    <!-- *** AOP -->
    <aop:config>
        <aop:pointcut id="accountServiceMethods" expression="execution(* de.appsiting.fashion.service.AccountService.*(..))" />

        <aop:advisor advice-ref="tx.advice" pointcut-ref="accountServiceMethods" />
    </aop:config>
</beans>

現在,當運行我的AccountTest時 ,accountService為null,因此測試失敗:

import de.appsiting.fashion.service.AccountService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.Test;


/**
 * Created by mak on 4/22/16.
 */
public class AccountTest {
    private static Logger log = Logger.getLogger(AccountTest.class);

    @Autowired
    private AccountService accountService;

    @Test
    public void testCreateAccount() throws Exception {
        Account account = new Account();
        account.setUsername("testfashion");
        account.setPassword("testfashion");
        account.setEmail("test@appsiting");

        accountService.addAccount(account);
    }
}

為什么會這樣?

您應該使用SpringJUnit4ClassRunner來初始化應用程序上下文,以便依賴項注入能夠運行。

另一個選擇是使用Mockito ,它在恕我直言中避免了很多麻煩,並且您獲得了使用模擬的好處。

您在測試中缺少兩種配置。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"Location of xml files that you need to load for tests to run"})
public class AccountTest {

}

以上配置將為您的測試加載上下文。 或者,您可以在設置方法中加載測試的應用程序上下文,然后使用該上下文獲取帳戶服務。

我認為您應該在serviceBeans.xml中添加以下內容,

<bean id="accountDao" class="de.appsiting.fashion.persistence.AccountDao" />

並刪除AccountService類中的@Autowired AccountDao批注,並添加一個AccountDao的設置器。

暫無
暫無

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

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