@Dependent
One of the scope annotations of CDI. The life cycle of the scope is "Follow the scope of the bean to inject"
The above description. For example, if the bean to be injected is @RequestScoped, the bean of @Dependent also behaves as @RequestScoped. I think you can get it.
In fact, this is a mistake!
For example, there is the following code.
MainBean.java
@RequestScoped
public class MainBean {
@Inject
private HogeBean hogeBean;
@Inject
private FugaBean fugaBean;
public void execute(){
hogeBean.setMethod(); // 1
fugaBean.method(); // 3
hogeBean.printMethod(); // 6
}
}
HogeBean.java
@RequestScoped
public class HogeBean {
@Inject
private DependentBean depBean;
public void setMethod(){
depBean.setId("ID set in HogeBean"); // 2
}
public void printMethod(){
System.out.println(depBean.getId()); // 7
}
}
FugaBean.java
@RequestScoped
public class FugaBean {
@Inject
private DependentBean depBean;
public void method(){
System.out.println(depBean.getId()); // 4
depBean.setId("ID set in FugaBean"); // 5
}
}
DependentBean.java
@Data
@Dependent
class DependentBean{
private String id;
}
Suppose the MainBean execute is executed from somewhere.
It will be like this.
Dependent Bean is considered to be a Bean of @RequestScoped if it is interpreted that the scope is the same as the scope of the Inject destination. @RequestScoped object uses the same instance in one request The value output in 4 above should be the value set in 2., and the output in 7. should be the value set in 5.
So the output result is
console
ID set in HogeBean
ID set in FugaBean
Should be.
However, in reality, the output result is
console
null
ID set in HogeBean
It will be.
The survival time of @Dependent is
Is the correct answer. The depBean is generated when the hogeBean is generated, The depBean is destroyed when the hogeBean is destroyed. Also, The depBean of hogeBean and the depBean of fugaBean are separate instances.
To put it very roughly, it's the same image as creating a new instance in a field. (Of course, it is not handled differently because it is not CDI managed)
There is basically no problem with circular references between CDI-managed beans, but if you make circular references between @Dependent beans, an error will occur when the server starts. This is because the bean on which it depends cannot be found.
If you think about it carefully, what happens when there is @ApplicationScoped or @SessionScoped in the Inject destination? That's right, but there were many people around me who misunderstood.
When you divide the components by domain, you can have different states for each, so it seems that you can use it well.
Recommended Posts