3

How jsf or any framework creates beans using annotation? Like jsf when we are using @ViewScoped, it's creating bean for every view or @RequestScoped creats bean for every request, how exactly it works internally?

dsahoo188
  • 61
  • 1
  • 7

1 Answers1

1

This is my understanding:

To explain easily, Assume we are trying to create such framework, which is capable of reading annotations and inject / create beans dynamically.

First part, we should have our own annotations / have to follow any standard annotations such as Java Validation API JSR303

Second, we should read the annotations at startup and cache these information in some colletcions which ever suits for us. if it for Web application, i would create a listener and instruct the developers to start the listener while starting the app ( or startup servlet .. lot of options) This class / listener/Startup servlet would read all classes ( may be we can provide some xml file where we can ask them to configure the details) / read the config files and read the annotations using Java Reflection API .

At this moment, we have required details. Such as

MyBean Location :com.bean Scope : request /hotelRegister

MySecondBean Location :com.bean Scope : Session /hotelRegister

So for each request we have to create MyBean if the related url request. and MySecondBean should create the only once per session.

Now the creation / manage the life cycle of bean. But where and when ?

Frameworks like JSF / Spring / Struts used to have single entry point to the web application. which needs to be configured in web.xml as startup servlet.

Assume we are having one Servlet ( MyServlet) which needs to be configure as startup Servlet.

So any request through this servlet would go via doPost or doGet method in this method.

in these method, we should be able to find what is the resource requested ( for example say /hotelRegister configuration ). From the configuration this servlet would know they have to create myBean as request scope , So using reflection it would create myBean and call the crossponding method in that Bean. and this servlet maintain the instance life cycle. once the request serviced this object removed from scope ( for example this object may put in HttpRequest attribute).

if its metiond as session , then the varaible would be kept in session and you should have sessionListener to handle the life cycle of bean.

Using Refelction we can create beans

So overall, it is easily to create objects based on information from configuration ( annotations / xml file / any format) using reflection. The key is , client should call / invoke operation via the context the framework provided.

I may explained in very very high level, but there are other functions such as proxy, AOP , caching , initialize ( DI) and lot of features comes with frameworks

Community
  • 1
  • 1
Mani
  • 3,274
  • 2
  • 17
  • 27