Spring - Autowire 服务到 POJO

Kil*_*ata 5 java spring spring-mvc

我有一个模型,我想在其中注入我的服务。

我的模特

@Configurable
@Entity
@Table(name = "user")
public Class User {

@Autowired
private UserService userService;

{
   System.out.println("Trying Service : " + userService.getMyName()); 
}

}
Run Code Online (Sandbox Code Playgroud)

在这里,我总是NullPointerException在第 7 行得到一个。

在我的 spring-context.xml 我有:

<context:spring-configured/>
<bean
    class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
    class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
Run Code Online (Sandbox Code Playgroud)

编辑

用户服务

@Component
public Class UserService {

  public String getMyName() { return "it's Me!";}

}
Run Code Online (Sandbox Code Playgroud)

dev*_*Fun 5

Spring 管理的组件只能连接到 Spring 管理的另一个 bean 中。

然而,如果您确实需要的话,有一个技巧可以将服务添加到 POJO:

  1. 使用 setter 将 UserService 作为静态字段添加到 POJO
  2. 在UserService中,spring初始化bean后,将其自身设置为POJO上的字段(这可以在@PostConstruct方法中完成)