【发布时间】:2019-06-18 21:31:11
【问题描述】:
语言/框架:Java8/Spring 4.3.9/openjpa 2.4.3
作为春季新手,我怀疑我在这里没有应用正确的模式。
场景类似于下图所示。但是,我无法初始化 objectB 并引发 Null Pointer exception。我怀疑问题在于 Spring 无法初始化 A 类,但我无法将“@Component”注释设置为 A 类,因为它没有默认构造函数。这种情况有解决方法吗?也许应该遵循的模式?这是使用 Spring 改造的遗留代码。
@ContextConfiguration(locations = { "classpath:/context.xml" })
ClassTestA{
@Test
public void TestA(){
:
:
A a = new A ("A", "B", "C", "D");
:
:
// Following line, Throws a null pointer exception in the doSomething() method.
someobject.someMethod(a.doSomething());
}
}
class A {
@Autowired
private B objectB;
public A (string t, string m, string x, string y)
{
// variable inits
}
// C class represents a database table Entity
public C doSomething()
{
C c = new C();
c.someWork(objectB.method()); // throws a null pointer exception because obJectB is null !
}
}
@Component
public class B
{
// No constructor
}
【问题讨论】:
-
如果您可以分享您的 xml 文件,那么我可以给您正确的答案。您不能将 static 关键字与 @autowired 注释一起使用。您可以尝试不使用静态关键字。您可以查看给定的链接以了解为什么我们不能在 spring 中自动装配静态字段。 stackoverflow.com/questions/10938529/…
-
@Gaurav - 删除了 static 关键字,但问题仍然存在。
-
“空指针异常被抛出”——在哪里? “我无法将“@Component”注释设置为 A 类,因为它没有默认构造函数” - 它需要一个,除非您也可以自动装配构造函数参数,例如来自配置文件的
@Values。跨度>
标签: java spring javabeans openjpa