Spring refresh context performance consideration - java

I am trying to use #RefreshScope annotation in my project, but I am not sure during the refresh, my application will freeze or not. I do not find any document about it in the web. Any thoughts is welcomed.

I found below article helpful in understanding how RefreshScope works. A quote from the same:
If you declare a #Bean having this scope, Spring Cloud will wrap that bean in a proxy class, which is what other components will actually get injected with. This proxy will just be proxying every method of the component to the real implementation.
Whenever there is a refresh event in the application, all the RefreshScope proxy beans will mark their underlying bean (the real implementation) as dirty. This means that whenever any of the methods of the proxy are called, it will first re-create the underlying bean, and then it will forward the method call. This re-creation of the bean would mean that it reads the configuration again. It’s important to make sure that #RefreshScope beans are lightweight, since refresh events will trigger re-construction of these beans.
https://dzone.com/articles/spring-cloud-config-series-part-1-introduction

Related

How are IoC and DI used in Spring MVC

I’m taking this udemy course all about Spring Hibernate etc. The course started with explaining how Injection of Control and dependency injection works not in a web perspective just like having simple classes or beans, defining beans and their dependencies inside a config xml file or inside the actual class Using java annotation and then a main class where the beans are created. I understood that despite not really seeing the big benefit of using IoC and DI other than separating roles like creating and maintaining objects and adding dependencies the object needs and I guess when the project is bigger this makes it cleaner and easier to follow right?
However what I don’t understand is how IOC and DI ties in a full spring MVC project. Like I understand using the #Controller annotation means it’s like an #Component and you could make it scan the components automatically when it creates beans but like unlike before there isn’t a main class where beans are created and configured rather I have a controller class where I manually create objects and models and pass that back to the views where I can use the values in the model. I don’t see how I use IoC or DI here? Or is it because it’s a simple project and perhaps the objects we created didn’t have many dependencies?Or are a lot of the uses and implementation done internally or automatically?
I am just struggling to a) see why IoC and DI are that important and b) how are they actually used in a Spring MVC project where you don’t have a main class where you do create beans.
A) Create a project, but don't add any dependency (or web-mvc). Then do it yourself then see how much need time to create configure manually. If it is just a simple mvc project, you can do it manually, but if your project increase day by day then a huge configuration file to maintain your project properly. But when you are professional developer, you don't have so much time to configure all those manually. So here is come the solution IoC and DI. Controller or other anotation are configured in build-in jars. You don't have to worried about to create controller or to create bean, just use them when you neer them. It's save your time as well as headache about is it working or not. It's increase your productivity while your are working on a big project.
B) Yes, there is no main class in web project. To run a web project, you need a server. The server first looking for a configuration (In spring, it's web.xml, dispatcher-servlet). If it available then expand the configuration file, if not then throw an error. In that configuration file, explain everything about the web project. What should do, what is not mandatory, what is entry point etc.
So, IoC and DI are very important because to understand how a web project work behind the scene or how all component work together.
IoC is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application.
The advantages of this architecture are:
decoupling the execution of a task from its implementation
making it easier to switch between different implementations
greater modularity of a program
greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts
Inversion of Control can be achieved through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).
You can go with Annotation based configuration, where you can define #Configuration class and return the required beans using #Bean annotation.
Also you can use #Component to your POJO class to treat it as Spring bean.

Letting Spring Boot manage the lifetime of my objects

I am new to Spring Boot and still trying to grasp best practices. What attracted me was Spring Cloud Configuration. Initially I wanted to do a hybrid implementation (due to the size of the existing code base) of Spring Boot but it inevitably lead me to a bunch of code smell and anti-patterns.
Before Spring, I was managing my own objects but I've quickly realized that Spring wants full control of object instantiation and ownership where there is dependency injection (which I understand). However there are some cases where I cannot let Spring completely drive but still have a dependency on configuration (e.g. another framework responsible for object management).
I don't want to do a one off scenario where I end up passing configuration through a chain of constructors and I want to avoid using AutowireCapableBeanFactory::autoWireBean(...) to manually wire my beans. At the same time, relying on Spring to manually initialize all my objects is a nuisance. To be clear, this is what I am talking about:
#SomeOtherFrameworkThatOwnsThisObject
#Configuration
public class SomeClassDeepInMyProject implements SomeKindOfInterface {
#Autowired
private ConfigurationController config;
...
}
I considered creating a singleton configuration provider that is accessible application wide and manually wiring the configuration bean to the class. If there is a better alternative, I am all ears.

Concurrency control with method invocation in EJB bean vs. Spring bean

EJB container serializes all business method invocations by default. And we have a couple of options to change it.
Apply the #Lock(LockType.READ)/#Lock(LockType.WRITE) annotations.
Or set #ConcurrencyManagement(ConcurrencyManagementType.BEAN) annotation on the bean class and use our custom synchronization policy (use syncrnozied blocks or don't use locks at all if bean only reads data, for example). The #Lock annotations is ignored in this case.
My question is how does Spring control it? How does it work be default?
Spring bean may be a stateless bean or may have a state. It can access some resource with read or write operations. And in different situations I need an option to control concurrency.
Could you please explain and compare this aspect of EJB/Spring containers.
EJB declarative concurency management applies only to singleton session beans, see javax.ejb.ConcurrencyManagement API. Regular session beans have no thread safety issues because containter insures that only one thread accesses a bean instance at any given time. As for Spring beans concurrency is not managed by container, programmers themselves should take care of it.

Get an Guice Injector in a web application

I'm looking how I could get an Injector using Guice in a web application. I already found a solution using ServletContext, but I'm not really satisfied by this solution, because it breaks the layer architecture of the application. I'm not okay with using a ServletContext in the deeper layers of the app. Do you know another way?
An obvious solution would be to create my own singleton to host the Injector, but it seems to be that Guice should offer some out-of-the-box way to do this. I just can't find one yet...
Assuming you're using Guice Servlet and assuming the class you want the Injector in is injected itself, just inject the Injector.
Your application lifecycle is fully controlled by the servlet container, so the usage of a context listener to start the initialization process of your application is the logical result of that fact. Thus I wouldn’t say that that fact in itself is not breaking the layered architecture, just like a web request starting activity in the model layer neither breaks the layered architecture.
But in order to not break the layered architecture, the servlet context listener shouldn’t involve itself with the details of the other layers, it should only initiate the initialization. Thus all Guice related code, for example a Guice injector factory, should be located in its own layer. The role of the context listener should be limited to a call that starts the initialization (for example: MyGuiceFactory.init() or MyApp.init()).

java ejb3 #PostConstruct

I am experimenting with EJB3 on JBoss, developing a stateless bean. Basically once the module has been deployed I need to perform some actions related to load application settings.
To do this I've annotated a method as #PostConstruct, which as far as I know from the API instructs the container to invoke it once the bean has been deployed and before get in service. (correct?)
Now, I am confused, because from the log on that method looks like is not simply called after has been deployed but before each exposed method is called.
I only need to call that method once, not every time it receives a call. What would be the best approach?
Thanks in advance
Alessandro Ilardo
A stateless bean should be just that - stateless. Meaning that in use, you should neither be able to tell or to care if the bean was pulled from a pool or constructed on demand for your request. I'm hard-put to envision how a PostConstruct could apply to a stateless environment, since I always use that function to finish building a bean's state.
Apparently, JBoss is either forgoing the pooling of stateless beans and constructing them fresh each time, or, if it is using pooling, treating them like they were reconstructed each time (since they shouldn't be carrying state information). I'm actually a little surprised that it invokes the PostConstruct at all.
First of all PostConstruct is called before first method will be invoked on the bean. If no method will be invoked no post construct ever be called.
Secondly you can execute inverse actions in PreDestory method to remove side effects.
Anyway which kind of action you have to perform?
It is up to the app server to manage the lifecycle of EJBs. It may decide to construct, initialise and tear down beans whenever it sees fit. It may be that each call to your stateless bean is on a fresh instance of the your bean class, although that does seem like an off thing to do.
Is the app server calling the #PostConstruct method multiple times on the same object instance, or on a different instance each time? Try sticking log statements inside the constructor and the #PostConstruct method.
How many SLSB do you have in your pool? Depending on the container the #PostConstruct may not be called until the first client accesses it (not sure about JBoss) so this may be why it looks like it is on every access. It would be interesting to see if it stopped calling your post-construct method after calling your method the number of times equalling your pool size.
If you are performing some expensive actions in your post-construct method then maybe do these in a SFSB at startup and "inject" that SFSB into your SLSB in the post-construct.
PostConstruct gets called before the client runs a biz method. This means that if the bean isn't pooled the container will instantiate the bean, do injection, call the #PostConstruct method, then allow the biz method to run.
In the case of a pooled be then the #PostConstruct method will be run every time the bean is pulled from the pool. With Stateless beans this will be between every method call. With Stateful beans this will be after client lookup or injection.
If you need to run something on application deployment your options will depend on the version of Java EE you have.
For Java EE 6 you can use #Startup on a #Singleton EJB which contains a #PostConstruct method.
For Java EE 5 and previous you'll have to use a ServletContextListener in a web archive. You can have the ServletContextListener call an EJB if you want.
However what might be a more important question is where do you want to load these application settings to? If you are dealing with a non-clustered single JVM configuration then you probably going to want to load them into a Singleton of some type. In Java EE 5- you'll have to implement the singleton design pattern yourself or in EE 6 use the #Singleton EJB type.

Categories

Resources