我有一个单元测试和一个助手类。不幸的是,Helper类的自动线不能工作。它在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个这样的对象,不同的测试有不同的对象。那么,在Helper类中使用@Autowired需要做些什么呢?谢谢!
发布于 2015-11-03 19:58:37
您不能通过new
语句创建Helper
类,但必须让spring创建它以成为spring by,因此它的@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(){...}
}
发布于 2015-11-03 19:55:12
您的Helper类不是由spring实例化的。您必须添加一个类似@component的注释(如果您使用的是package scan),或者您可以在springconfiguration类中将该类定义为Bean。但是,如果您自己创建实例,它将无法工作
https://stackoverflow.com/questions/33498433
复制相似问题