Using Springs IoC in this case? - java

I am curious on the way Spring is able to bind together an application (just in simple terms of course). In a standalone Java application you bootstrap the application with a lookup then Spring instantiates and binds the objects together (DI).
If you for example have a for loop where you don't know the number of iterations (user input) would you use the dependency lookup method inside the loop body? And would you implement the BeanFactoryAware interface in this case? Or do you make the object by using new keyword?
Just an thing that came to my mind while reading.

"Lets pretend that you need a new instance each time"
If you have a component A that has a for loop where you need a new instance of a "bean" B on each iteration, why not just inject a B factory into A and call that within a for loop.
It all really comes down to what makes sense:
If you need to create something simple (e.g. a new String) on each iteration, then there is nothing wrong with using a new keyword.
If it is something more complex, where it is best to encapsulate "creation details", it would not do you any good to depend on any particular framework (e.g. BeanFactoryAware). Just use a builder/factory, which can either be another bean that would be injected, or can be called statically.
Less magic more clarity

If I understood your question correctly the answer could be: Spring beans are singletons by default.
So in most cases you would never need to lookup one inside the for loop - you'll use the instance looked up just before your loop.
Also you're probably trying to think about Spring beans as JavaBeans that you create to populate with data. You could read this link to see the difference: http://www.shaunabram.com/beans-vs-pojos/
Spring beans are more like JavaEE Enterprise Beans, you don't create them - you just use them.

Related

JAX-RS Resource Lifecycle Performance Impact

I know by default JAX-RS endpoints lifecycle is once-per-request, so that the request specific informations can be injected into the instance.
And we can also make an endpoints Singleton meaning once-per-application, in which the request specific informations cannot be injected into the instance rather it can be injected into the requested method.
1. So i would like to know which approach is better in terms of performance, either once-per-request or once-per-application.
2. I would also like to know the pros and cons of these approaches other the injecting request specific informations
3. Which approach you prefer to use in your API applications
Note: i have been using the once-per-request approach so far, but i always wonder is that is efficient, definitely its make coding easier and reusable.
To start with your last question: I'm always using the default (per-request) and I seldom came to a point where I wanted to change this.
What might be a reason to prefer one over the other?
If you want to serve some static content (maybe a welcome-document of your API) it makes sense to produce this content only once and hold it in a singleton resource class. But you can achieve the same by e.g. injecting an #ApplicationScoped CDI bean in a per-request scoped resource class.
If you prefer injecting the #xxxParam values like #QueryParam as fields instead of method parameters you should use the per-request lifecycle. This is not supported for singletons. (This does not include injecting via #Context).
I made a little test to compare the performance of both. You can find the sources and the results on github. In short: I measured a difference from about 1.5 %. I don't think this should affect your application too much.
Comparing the results of the JVisualVM monitoring I would tend to say that the per-request test is using more memory but you should decide on your own if this really affects your application.

How to ensure a class can only be instantiated by Spring?

I am re-factoring a legacy Java application to use Spring.
This involves declaring the application classes as Spring beans and then replacing all occurrences of new with context.getBean OR with DI.
I'm re-writing application logic in way that some classes become singletons. However since they are being instantiated using new in other locations, multiple copies would exist which would mess up the business logic.
I'd like to ensure that application explicitly fails whenever it tries to instantiate an object by itself, instead of running and misbehaving in unpredictable ways. (I'm not sure that the re-factoring has covered 100% of the application there still might be new lurked up in some corner)
What is the best way of ensuring that a class can only be instantiated by Spring container?
(I'm hoping to avoid writing a factory for each class)
As from your question
In this particular scenario only one copy of an object should exist which is fetched from the context, multiple copies would mess up the business logic.
you can create classic singleton and use getInstance() method as factory method in bean definition in spring's xml file:
<bean id="myBean" class="MyClass" factory-method="getInstance"/>
Make your constructor private, and than no one can call it. Additionally you will see errors in compile time, if some parts of old code uses new to instantiate your class.

Why does StockWatcher.java use class variables instead of local variables in onModuleLoad?

So, yeah. That. I'm going through the tutorial one step at a time, so if the answer comes up later, forgive me. It's step 1 in this section.
I understand the ease of using this to have access in other methods in the EntryPoint class, but coming from the Spring MVC world, this sort of thing might be thought of as a controller and be a singleton (bean). Is it wrong to think this way in the GWT world?
With GWT you are coding as if it was a desktop AWT program. So, you do not have CDI or anything similar.
So, if you put all your information in a bean, you still would have to either:
keep a bean attribute in the class
pass it as a parameter in the method call
to get a reference to it (instead of retrieving it from CDI when needed)
While you can still use a bean when needed, these attributes are closely linked to the main class (in fact they are other graphical components to show). In general, I would only use bean when you have a bunch of attributes that are tightly coupled between them but are not tightly coupled to any other class.

Dependency Injection in every aspect of a spring app?

I am taking a look into Spring as a web framework, however I am needing a bit of help getting my head around DI.
The concept of objects getting constructed in the container on run time is such a new concept.
I am just wondering how this will reflect in a big application, would I have some modules doing work that are more highly coupled or should every object be initialised at runtime?
It all seems a little intensive to me, I mean say for example I have a CSV file data mining application that removes the data per row - each rows data is encapsulated in one of my own CSVRow objects for processing or whatever. These objects are instantiated whenever an Excel file maybe uploaded to the server. I don't know how many I will need to create?
I seem to be getting a bit lost, any clarity, an overview or some guidance would be much appreciated.
Thanks in advance!
I'll try to put it simply:
use dependency injection for stateless classes that have logic (business logic, persistence logic, front-end logic)
use new for value objects
Broadly speaking, an application is made up of a collection of classes that implement the business logic.
Normally each object is responsible to obtain references of the objects it needs (and this object's dependencies).
I think it is obvious that this leads to:
1) tightly coupled classes
2) code hard to test since each object instantiates specific classes it depends on and if there needs to be a change, the code must be modified.
So using Dependency Injections the objects do not instantiate the dependent objects themselves but an "external component" provides the dependencies at the object creation time i.e. injects the dependencies into the objects.
So in your example, the idea is that you can have for example a CsvRow object instantiated by Spring (along with all its dependencies) and get an object whenever needed. It is also possible to switch to for example CsvRow2 object (another implementation) by just changing your configuration
You don't need to use DI for your CSV row abstraction. Once you get the file, when you start parsing it, your code can create the CSVRow things as it goes. You don't need to wire them up.
You certainly could if you wanted to. You would grab your applicationContext and just get the beans by name. You would want to do this if the CsvRow had dependencies that you wanted Spring to manage for you.
I think of Spring as a way to create "singletons". When I want to guarantee there's only one instance of a class in the application, use Spring to create it. But, instead of being a traditional singleton with a static INSTANCE field or similar, it's a POJO with whatever constructors / setters you need. Spring creates the instance at runtime for you and makes sure that creation only happens once.

In what case would a programmer get the webApplicationContext out of DispatchServlet?

I notice that there is getWebApplicationContext in org.springframework.web.servlet.mvc.AbstractController. This means that spring programmers can use getWebApplicationContext to access beans in the spring IoC container.
However, I never see people use this way to get beans in all the spring MVC tutorials. So here comes my question, in that case would a programmer want to get the WebApplicationContext?
That's an odd question... are you asking why a method is in the API if none of the tutorials use it? Do you expect every API method to be in the tutorials?
The getWebApplicationContext() method is rarely used by application code, but it is used internally by Spring for some tasks.
In some cases when you implement org.springframework.web.servlet.View a call to getWebApplicationContext can be useful to get access to Spring beans that can not (or should not) be passed along in the Model object.
You also might need it when implementing custom JSP tags to access Spring Beans e.g. But this is usually a method you try to avoid from application code.

Categories