Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI 1.1 - Inject Dependent scope in ApplicationScope

Tags:

java

cdi

Say I have an @ApplicationScoped service class.

@ApplicationScoped
class MyCustomerService {
   ...
}

I then want to inject a Connection object into that service.

@ApplicationScoped
class MyCustomerService {
   private final Connection connection;

   @Inject
   MyCustomerService(final Connection connection) {
      this.connection = connection;
   }

   ...
}

The Connection object is produced by a @Produces method, using a DataSource.

class ConnectionProducer {
   ...

   @Produces
   Connection getConnection(final DataSource dataSource) {
      return dataSource.getConnection();
   }

   ...
}

Will the Connection class be proxied? Will CDI invoke the producer method each time I use the connection bean (not like RequestScoped, I really mean for each invocation)?

I know I could just @Inject the DataSource, this is just "learning" how CDI manages scopes.

like image 538
LppEdd Avatar asked Dec 31 '25 21:12

LppEdd


1 Answers

Will CDI invoke the producer method each time I use the connection bean

No. the producer method called once because the default scope is Dependent . your connection lifecyle bounded to MyCustomerService lifecycle

Will the Connection class be proxied

If the bean is in @Dependent scope, then the client holds a direct reference to its instance(clientproxy is just created for NormalScope)

but if the bean has decorator or interceptor a proxy will be created(client proxy is not created because there is not any context for selecting bean but another proxy is created for applying decorators and interceptors) I tested this at weblogic application server

like image 111
Mehran Mastcheshmi Avatar answered Jan 03 '26 10:01

Mehran Mastcheshmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!