2011-04-07 68 views
1

春天我有以下问题。我有一个web应用程序和一个域项目。域项目包含一个studentService,它应该通过webapp中的自动装配注入。我已经添加到appcontext.xml。春天自动装配失败,但appcontext解决豆

这是来自Web应用程序的类:

@Component 
public class JSONToDomainObjects 
{ 

@Autowired 
private StudentService studentService; 

private void bindSubmissionValuesToDomainObjects(Integer userKey) throws Exception 
{ 
Student student = studentService.getStudentBySlNumber(userKey); 
} 
} 

那么studentservice:

@Service 
public class StudentService 
{ 
    .. 
} 

所以一旦我启动我的应用我看到studentService为空,但是当我拿到appcontext并调用方法getBean(“studentService”)比返回studentservice实例。我使用spring 3.0.5。有人知道自动装配失败的原因吗?

欢呼声,

迈克尔

+0

如何连接你的'JSONToDomainObjects'类?你如何得到它? – 2011-04-07 09:31:52

+0

它最终会被@controller注解的控制器类调用,但此刻我有一个testng测试,它使用filesystemxmlapplicationcontext读取test-application-context.xml。那么我有一个测试,目前正在通过new关键字实例化jsontodomainobjects,如:JSONToDomainObjects converter = new JSONToDomainObjects();然后在转换器对象上调用方法bindSubmissionValuesToDomainObjects – 2011-04-07 09:51:16

+0

或许你是对的,我正在做的是实例化jsontodomainobjects类,我想这并没有触发自动装配或什么。这个理论是否正确? – 2011-04-07 11:00:50

回答

1

是否使用你的appcontext.xml <context:annotation-config/>

+0

yes我的appcontext中有该标记 – 2011-04-07 09:55:32

+0

?指定的软件包是否包含StudentService的软件包? – 2011-04-07 11:37:19

+0

是的,但我认为问题在于如上所述的测试方法 – 2011-04-08 07:56:54

2

为什么不在测试类中使用依赖注入?类似这样的:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"appcontext.xml"}) 
public final class JSONToDomainObjectsTests { 
    private StudentService service; 

    @Autowired 
    public void setService(StudentService service) { 
     this.service= service; 
    } 

    @Test 
    public void testJSONToDomain() { 
     service.foo(); 
    } 
} 
相关问题