我有一个单元测试和一个助手类。不幸的是,Helper类的autowire不起作用。它在MyTest类中运行良好。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:context.xml"})
@Component
public class MyTest {
@Autowired
private Something something1;
@Autowired
private Something something2;
..
@Test
public void test1()
{
// something1 and something2 are fine
new Helper().initDB();
..
}
}
// Same package
public class Helper {
@Autowired
private Something something1;
@Autowired
private Something something2;
..
public void initDB()
{
// something1 and something2 are null. I have tried various annotations.
}
}
我想避免使用setter,因为我有大约10个这样的对象,不同的测试有不同的对象。那么,让@Autowired在Helper类中工作需要什么呢?Thx!
您不能通过new
语句创建Helper
类,但必须让spring创建它才能成为spring-been,因此它的@Autowired
字段会被注入。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:context.xml"})
@Component
public class MyTest {
@Autowired
private Something something1;
@Autowired
private Something something2;
..
@Autowired
private Helper helper
@Test
public void test1() {
helper.initDB();
}
}
//this class must been found by springs component scann
@Service
public class Helper {
@Autowired
private Something something1;
@Autowired
private Something something2;
public void initDB(){...}
}
您的Helper类没有被spring初始化。。。您必须添加像@component这样的注释(如果您使用包扫描),或者您可以在springconfiguration类中将该类定义为Bean。但是,如果您自己创建实例,它就不起作用