简体   繁体   中英

Weld @Inject ApplicationScope bean creates new instance in every inject point

I'm trying to understand CDI using Weld. Got the next structure:

@ApplicationScoped
public class MainFacade {

    @Inject
    private FooFacade fooFacade;

    private static int ins=0;

    public MainFacade() {
        super();
        ins++;
        System.out.println("MainFacade instance = "+ins);
    }

    public FooFacade getFooFacade() {
        return fooFacade;
    }
}

Where FooFacade is also @ApplicationScope.

When app is starting I've get a MainFacade instance = 1. When I inject it in other class (GWT RPC servlet) and call mainFacade.getFooFacade() then new instance of MainFacade are created along with a new instance of fooFacade.

Thought that Weld would return me the same instance of application scope bean anywhere I inject it. What I'm doing wrong?

I don't think this test will work well to verify that an application scoped bean is really a "singleton".

If you inject this bean into other beans, Weld will create a proxy which will handle the delegation of all invocations to the correct instance. This is important especially if you inject request scoped bean into session scoped beans for example.

The proxy will basically extend MainFacade which is required because otherwise the proxy cannot be injected into the fields where the injection is happening. When creating an instance of the proxy, the default constructor of you bean will be executed. As Weld will create many proxies, you are seeing multiple logs to the console. You could verify this by adding something like this to your constructor:

System.out.println("Type: "+this.getClass().getName());

使用@ApplicationScoped时,Weld会创建一个也调用构造函数的代理, 这里是规范

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM