@Component
public class AnnotationTest extends TestCase{
ServiceTest serviceTest;
@Autowired(required=false)
public void setServiceTest(ServiceTest serviceTest) {
this.serviceTest = serviceTest;
}
public void testAnnotation() {
new ClassPathXmlApplicationContext(new String[]{"/com/test/spring/ioc/beans.xml"});
serviceTest.annotationTest("testName", "testPassword");
}
Exception in thread "main" java.lang.NullPointerException
at com.test.spring.ioc.AnnotationTest.invokeIoC(AnnotationTest.java:16)
at com.test.spring.ioc.AnnotationTest.main(AnnotationTest.java:13)
服务类:
@Service
public class ServiceTestImpl implements ServiceTest{
@Autowired
AnnotationDAO annotationDAO;
public List<String> annotationTest(String name, String pssword) {
return annotationDAO.annotationTest(name, pssword);
}
}
DAO类:
@Repository("AnnotationDAO")
public class AnnotationDAOImpl implements AnnotationDAO{
public List<String> annotationTest(String name, String pssword) {
List<String> list = new ArrayList<String>();
list.add("Test 1");
list.add("Test 2");
return list;
}
}
beans.xml中:
<bean id="service" class="com.test.spring.ioc.service.ServiceTestImpl"/>
<context:annotation-config />
<context:component-scan base-package="com.test.spring" />
我该如何解决这个问题?
编辑:
它被给予警告消息:
WARNING: Autowired annotation is not supported on static methods: public static void
com.test.spring.ioc.AnnotationTest.setServiceTest(com.test.spring.ioc.service.ServiceTest)
如上通过添加@Component I所示移动到JUnit测试而不是Java主要方法(我不知道这是必需)。 现在我得到新的错误为:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'annotationTest': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field:
com.test.spring.ioc.service.ServiceTest com.test.spring.ioc.AnnotationTest.serviceTest;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
unique bean of type [com.test.spring.ioc.service.ServiceTest] is defined: expected single
matching bean but found 2: [service, serviceTestImpl] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProce ssPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
我没有意识到这是进入单元测试,这可能会帮助http://stackoverflow.com/questions/6546871/spring -junit-testing – beny23