@Injected @ManagedBean gets reinitialized despite of @ApplicationScoped annotation

倖福魔咒の 提交于 2019-12-06 15:45:51
BalusC

@Inject only injects CDI managed beans.

@ManagedBean declares a JSF managed bean not a CDI managed bean.

Make the Rates class a CDI managed bean instead.

import javax.inject.Named;
import javax.enterprise.context.ApplicationScoped;

@Named
@ApplicationScoped
public class Rates {}

Noted should be that the general recommendation is to stop using JSF managed bean facility and exclusively use CDI managed bean facility. So it'd be better if you make all your other JSF managed beans CDI managed beans too. That's exactly why I wouldn't recommend to replace @Inject by its JSF equivalent @ManagedProperty (which would also have worked).

As to managed bean initialization, you should not do it at class/instance level, but perform the task in a @PostConstruct annotated method.

private Map<String, Double> rates;
private Set<String> currencies;
private List<String> list;

@PostConstruct
public void init() {
    rates = new HashMap<>();
    currencies = new HashSet<>();
    list = new ArrayList<>(Arrays.asList("Filip", "Kasia"));
}

This is particularly important in CDI because it creates and injects proxies based on the class, so the class may be instantiated at times you don't expect.

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!