2

在遵循示例之后,这适用于 JUnit 测试:

@ContextConfiguration(locations = "classpath:/spring/context.xml")
@RunWith(SpringJUnit4ClassRunner.class)  
@Transactional  
public class ServiceTest  {
    @Autowired
    private Service service;

    @Test
    public void doSomething() {
    assertEquals(0, service.getNumber()); ...
    }

当我尝试将其移至非测试代码时,这不起作用:

// @ContextConfiguration only works for testing (JUnit).  What do I use here, instead?  
// @ContextConfiguration(locations = "classpath:/spring/helloWorldContext.xml")  
@Service // supposedly to get the Spring Container to 'see' this class
public class Accessor {      
    @Autowired( required=true )      
    private Service service;

    @Autowired
    public Accessor() {
    return service.getNumber(); ...
    }

基本上,我想以与使用测试类相同的方式使用非测试类。

4

2 回答 2

0

您可能需要通过将其添加到您的 spring 配置文件来启用 annotation-config:

<context:annotation-config />

文档: http ://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-annotation-config

于 2013-03-17T21:20:58.750 回答
0

据我所知,您不能对普通 bean 执行此操作,但您可以创建@Configuration类并将其放在您的 bean 旁边:

@Configuration
@ImportResource("classpath:/spring/context.xml")
public class ServiceConfiguration {}
于 2013-03-17T21:26:21.847 回答