Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Autowire Service into POJO

I have a model in which I want to inject my service.

My Model

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

@Autowired
private UserService userService;

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

}

Here I get always a NullPointerException on 7'th line.

In my spring-context.xml I have :

<context:spring-configured/>
<bean
    class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
    class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

EDIT

UserService

@Component
public Class UserService {

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

}
like image 607
Kilo Batata Avatar asked Jun 15 '17 11:06

Kilo Batata


People also ask

Can we use @autowired in pojo?

Yes this is possible with the @Configurable annotation and some byte-code magic.

Can we use @autowired in service class?

Spring @Autowired Annotation - Service ClassWe will use the same service class for perform spring autowiring byName, byType and by constructor. The setter method will be used for spring autowiring byName and byType whereas constructor based injection will be used by constructor autowire attribute.

What is difference between @autowired and @resource in spring?

The main difference is is that @Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.

What is difference between @autowired and @inject?

@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application. Sr.


1 Answers

Spring managed components can be wired only into another beans managed by Spring.

However, there is a trick to add service to your POJO if you really need it:

  1. Add UserService as a static field to your POJO with a setter
  2. In UserService after spring initializes the bean, set itself as a field on the POJO (this can be done in @PostConstruct method)
like image 148
dev4Fun Avatar answered Oct 24 '22 02:10

dev4Fun