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

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.

Related

Difference between a global variable and an injected variable?

Is it common practice to communicate via field references. Let's say I have an instance injected all over my program. Since all classes are referencing the same instance I can simply change it's state, instead of informing all dependent classes via method calls? Isn't that a big advantage of dependency injection? Or do I turn a dependency injected variable turn into a global variable?
Variables don't get injected. Values get injected. When you inject a bean into another bean you are injecting that reference. References are values, see
Is Java "pass-by-reference" or "pass-by-value"?.
You can have some spring bean in singleton scope that different parts of the application call, with some method which returns a value. For instance a spring boot application can have a Clock configured that various services or other components have injected into them, where they call the clock to get the current time.
If you do have a bean that contains some mutable value that gets set, be aware its scope will be limited to the application instance. If you have multiple instances of the application deployed. each one will have its own separate bean. Also changes aren't going to be guaranteed to be visible across threads unless you enforce that (with tools like locking, the volatile keyword, atomic variables, etc.).
Fundamentally OO is about message-passing, not about sharing memory. We want to limit global state because it's hard to reason about. Especially when you consider the high-concurrency of a web application and how quickly things can be changing, and how difficult it is to ensure changes are visible, in a lot of cases it's better to find alternatives to global variables.
Assuming that the injected type is configured to use a Singleton, there shouldn't be any behavioral difference between using dependency injection and accessing a Singleton directly.
The advantages to using Dependency Injection generally center around how the code is written, and how it allows you to decouple the consuming classes from the specific requirement for that injected object to actually be a singleton.
For example, if you want to unit-test your consuming class, you probably want complete control over what the class perceives as the current state, and you probably don't want any effects of the code your testing to carry over into other unit tests: you don't want a test to pass when it is run all by itself but fail if it happens to run immediately after some other test.
Using Dependency Injection, your unit tests can encapsulate the entire interaction with the code being tested. The code that instantiates the class has complete control over what gets injected, so it doesn't have to provide a singleton value.
By separating the class that consumes an injected value from any specific knowledge about where that value comes from, or what its life cycle looks like, you're better able to maintain separation of concerns. If a future change requires a value to no longer be a singleton (e.g. maybe it needs to be dependent on the current user), you're in a better position to change how that injected value is provided without having to change code all over your code base.

How to maintain a centralized Object across the application

I am developing an application where I need to create an object and multiple classes have to access and modify that object. How to see the recent changes made by the other class object and how to access the object centrally through all the classes with out passing that object as a parameter across all the classes?
I am creating an Apache POI document where I am adding multiple tables, multiple headers/footers and paragraphs. I want only a single XWPFDocument object present in my application.
Is there any design pattern we can achieve this?
Well the singleton design pattern would work - but isn't terribly clean; you end up with global static state which is hard to keep track of and hard to test. It's often considered an anti-pattern these days. There are a very few cases where it still makes sense, but I try to avoid it.
A better approach would be to use dependency injection: make each class which needs one of these objects declare a constructor parameter of that type (or possibly have a settable property). Each class shouldn't care too much about how shared or otherwise the object is (beyond being aware that it can be shared). Then it's up to the code which initializes the application to decide which objects should be shared.
There are various dependency injection frameworks available for Java, including Guice and Spring. The idea of these frameworks is to automatically wire up all the dependencies in your application, given appropriate configuration.
There is Singleton Pattern for this, it creates a single instance for the application and is shared without passing around.
But it not not the best of options.
Why is it a bad option?
It is not good for testability of code
Not extensible in design
Better than Singleton Pattern is an application wide single instance
Create a single object for the application and share it using some context object. More on this is explained by Misko in his guide to testable code
single instance and not Singleton Pattern
It stands for an application wide single instance, which DOES NOT inforce its singletonness through a static instance field.
Why are Singletons hard to test?
Static access prevents collaborating with a subclass or wrapped version of another class. By hard-coding the dependency, we lose the power and flexibility of polymorphism.
-Every test using global state needs it to start in an expected state, or the test will fail. But another object might have mutated that global state in a previous test.
Global state often prevents tests from being able to run in parallel, which forces test suites to run slower.
If you add a new test (which doesn’t clean up global state) and it runs in the middle of the suite, another test may fail that runs after it.
Singletons enforcing their own “Singletonness” end up cheating.
You’ll often see mutator methods such as reset() or setForTest(…) on so-called singletons, because you’ll need to change the instance during tests. If you forget to reset the Singleton after a test, a later use will use the stale underlying instance and may fail in a way that’s difficult to debug.

why should java beans be used? [duplicate]

This question already has answers here:
Places where JavaBeans are used?
(4 answers)
Closed 9 years ago.
I am new in j2ee and want to know about java beans. I have one java class, and use an instance of that class in another class. What are the reasons I should define the first class as a java bean and then inject an instance of that in another class? what are the advantages of that? What kind of classes are better to be defined as java beans? For example, I may have a pojo to be used in ORMapping, a class to make UI (I use vaadin to make UI) , another class to do business logic (for example, calculate the result specific mathematical formula) , and another class to do DB operations. Which one is the candidate to be defined as a java bean, using ejb or spring?
The JavaBeans designation only concerns the convention of providing accessor methods for the public properties of the class. POJO is an orthogonal concept and a Java bean may easily also be a POJO.
You seem to be contemplating beans in the context of the Spring IoC container. Spring uses the term "bean" in quite a loose sense and the actual objects may not even comply with the JavaBeans specification. Most typically they provide only a setter (no getter).
Now, the advantages of letting an IoC container wire together interdependent objects are many and this practice is warmly recommended. Some points:
the concern of bean instantiation is centralized;
less coupling between beans: the client bean doesn't need to know how to initialize its collaborators;
trivially easy handling of the otherwise massive problem of circular dependencies;
no boilerplate code involving instantiation sprinkled around code;
easy reuse of singletons => saves memory, brings order and consistency to the object system;
declarative control of bean lifecycle, again with no boilerplate code in the beans themselves.
From the javadocs:
JavaBeans™ makes it easy to reuse software components. Developers can
use software components written by others without having to understand
their inner workings.
To understand why software components are useful, think of a worker
assembling a car. Instead of building a radio from scratch, for
example, she simply obtains a radio and hooks it up with the rest of
the car.
Java beans is used to store data persistently in database. this class consist of setter and getter method. you need to create another java class to do this operation

Using Springs IoC in this case?

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.

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.

Categories