【发布时间】:2017-06-15 11:40:43
【问题描述】:
我有一个模型,我想在其中注入我的服务。
我的模型
@Configurable
@Entity
@Table(name = "user")
public Class User {
@Autowired
private UserService userService;
{
System.out.println("Trying Service : " + userService.getMyName());
}
}
在这里,我总是在第 7 行收到 NullPointerException。
在我的 spring-context.xml 我有:
<context:spring-configured/>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
编辑
用户服务
@Component
public Class UserService {
public String getMyName() { return "it's Me!";}
}
【问题讨论】:
-
请提供
UserService的代码和您的spring 上下文XML 文件,提供的信息不足以确定性地说明任何内容。 -
这不是将 bean 注入数据模型的好方法。为什么需要这种注射?
-
你需要在你的spring XML文件中有组件扫描和注释驱动的条目,比如
<context:component-scan base-package="com.cgi.itd"/> <mvc:annotation-driven />,我不知道@Configurable是否是spring注释使类成为bean与否,如果不是,则必须使用@Component或类似的spring注解 -
据我所知,Spring 不会在初始化时初始化任何
Entity。尝试调试异常以查看引发异常的确实是 Spring 还是来自您的代码 -
你不能那样做。初始化程序块是构造函数的一部分,在构造对象之后注入依赖项。您正在尝试在它被注入之前使用它。
标签: java spring spring-mvc