[英]java.lang.NullPointerException at object instantiation
我的應用程序使用struts和spring框架。 我有一個FormA
類,其中包含一個自動裝配的屬性。 當我嘗試在編寫單元測試時實例化它時,我得到一個空指針異常。 這是我的代碼。
我的班級A:
public class FormA{
private String propertyOne;
@Autowired
private ServiceClass service;
public FormA(){
}
}
我的單元測試方法:
@Test
public void testFormA(){
FormA classObj = new FormA();
}
@Autowired
僅在Spring管理對象生命周期時有效。
您需要使用@RunWith(SpringJUnit4ClassRunner.class)
運行測試,而不是手動實例化FormA
,使用@Autowired
將其注入測試類。
當你用new創建一個對象時,autowire \\ inject不起作用......
作為解決方法,您可以嘗試這樣做:
創建NotesPanel的模板bean
<bean id="notesPanel" class="..." scope="prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>
並以這種方式創建一個istance
applicationContext.getBean("notesPanel");
PROTOTYPE :這可以將單個bean定義范圍包含任意數量的對象實例。
無論如何應該進行單元測試
考試班
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {
@Autowired
private UserService userService;
@Test
public void testName() throws Exception {
List<UserEntity> userEntities = userService.getAllUsers();
Assert.assertNotNull(userEntities);
}
}
您-彈簧的context.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="userService" class="java.package.UserServiceImpl"/>
</beans>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.