W
W
Witold2013-08-09 13:43:29
Java
Witold, 2013-08-09 13:43:29

How does the @Inject annotation work?

Hello. I'll try to explain my question with an example.
There is an entity class displayed in the database, and a controller class for it:

public class Controller {
  @Inject
  private EntityManager em;
<...>
}

When creating an instance of this class:
<...>
  public void add() {
    Controller с = new Controller();
    с.save(new Entity("habrahabr"));
  }
<...>
field emis equal to null. (Hibernate is connected to the project as a provider.)
At what point in time and under what conditions does this annotation “work”?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vladimir Smirnov, 2013-08-09
@bobzer

At what point in time and under what conditions does this annotation “work”?
In order for the annotation to work, you need a configured data source deployed by the JBoss server before your application starts (which is achieved by specifying dependencies in your deployed module), as well as connecting your business logic as a module in the EAR, for which in application.xml specify
<module>
        <java>ваша-логика.jar</java>
</module>

And, yes, the @PersistenceContext or @PersistenceUnit annotation is usually indicated

E
eugenius_nsk, 2013-08-11
@eugenius_nsk

1. The @Inject annotation is related to and managed by CDI (reference implementation is Weld).
2. Any dependency injection framework requires beans to be managed through it; accordingly, it is impossible to create objects through new in the general case. If you need an instance of the Controller, create it the same way, via @ Inject.

T
tsegorah, 2013-08-09
@tsegorah

Why do you have Inject ? and not @PersistenceContext(unitName = "Blablabla") and so on? Maybe I misunderstood something in your question, but I always use @PersistenceContext.

K
kxyu, 2013-08-10
@kxyu

How does the Inject annotation work ?

No way. Annotations do nothing at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question