Is it bad practice for a spring-based jar project to provide a bean configuration file? - spring

If you have a library containing Spring beans that need to be wired together before an application can use them, does it make sense to include any sort of bean configuration file in the JAR (such as the /META-INF directory)? The idea is to give the application the option of importing this into its master Spring context configuration.
There may be more than one way to wire these beans, so I could provide a bean configuration file for each of the standard ways in which you'd typically wire them together.
Or, do I force the application to wire these up explicitly?
If it helps, the specifics of my problem involve a library I created to encapsulate our product's persistence layer. It contains Service, DAO and model beans. The DAO implementations currently use Hibernate (this probably won't change). Some of the DAO implementations need different kinds of Strategy beans injected into them (database encryption logic), depending on the type of database we are deploying on (MySQL vs SQL Server, etc). So we have potentially a few different configuration scenarios. I could also provide datasource bean configurations, relying on property substitution at the app level to inject all the particulars needed by the datasource.
Thanks for your input!

In this case, it's a good idea to provide some beans files, either as examples for documentation purposes, or as fully-fledged files ready for including into a wider context.
If your beans' wiring can get complex, then you shouldn't really leave it entirely up to the library client to figure it out.
This is more of a documentation and education task, really.

Related

Why does spring use ioc and di?

I'm new to spring 5 and my question is why does spring use DI and IOC? I mean why do we have to write the beans in an XML (legacy) and then create it where we need it? Why don't we use one method instead that gives us that object, until we want to use this complex mechanism that happens in the spring container?
And another question is, does not reading XML slow down the program? Because we are reading from the hard disk anyway.
Note: It is true that we can use annotations, but for now I want to ask a question about reading from xml.
Spring IoC Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML) or Java Code or Java Annotations and Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their lifecycle is not done by the developers, hence the name Inversion Of Control.
More on link HERE
As for your first part of the question.
why does spring use DI
To allow the developer to keep his code loose, and not entagle classes, it keeps your code clean.
In object oriented design, the amount of coupling refers to how much the design of one class depends on the design of another class. In other words, how often do changes in class A force related changes in class B? Tight coupling means the two classes often change together, loose coupling means they are mostly independent. In general, loose coupling is recommended because it's easier to test and maintain.
You may find this paper by Martin Fowler (PDF) helpful.
I mean why do we have to write the beans in an XML (legacy) and then create it where we need it
Note: We write the bean in XML and it is created when application starts when it looks at bean defintion, techinally you are never creating a bean, you are fetching only created bean from Spring Container(IOC) that Spring created for you when you started your application.
We are writing bean blueprint, or just bean, so that it can be constructed, placed in the Spring Container when the application starts, and then we have it at our disposal that we can fetch it using getBean method.
The whole point of "why", is because by default all beans are scoped as singleton, that means, when you fetch a bean, and do with it whatever you want, you do not worry about memory or anything, Spring takes care of the beans for you if they are scoped as a Singleton.
Second question:
And another question is, does not reading XML slow down the program? Because we are reading from the hard disk anyway.
There is no difference in performance between annotation or XML, it is just a different approach, I am not sure what you mean by "reading from hard disk", but one way or another you will have to configure your application, yes, many forums prefer to run away from XML, but in my honest opinion the only reason for that is because when you write a bad configuration in XML it is lot harder to find it compared to configuration in Java that will throw an exception.
XML, application.properties files require a redeployment of the application, while annotation and java configuration require recompilation of your project, so both of them have "flaws", but it is normal and quite understandable to me.
But in the end I believe that it is a matter of preference, I know personally quite a few people that combine annotations with XML configuration and they know lot more about Spring compared to me.
So in summary, it is pain to write beans and their configuration, same as you can write a class with methods without creating an interface for it since the result will be the same, but it will help you in the long run since you do not have to worry about memory or if you destroyed that bean or if you did not.
It would be nice that you read about
1.Lazy initialization of beans
2.Eager initialization of beans
3.Singleton scope of beans
4.Prototype scope of beans

Is Java Spring really better than straight up Java programming

I have read that dependency injection is good for testing, in that a class can be tested without its dependencies, but the question comes to my mind if Class A depends on Class B or C or any class, testing Class A independent of some class is yielding a test result of zero, not a failed or past test.
Class A was created to do something and if it is not fed anything whether using new key word or setting up the extra files in Spring, Class A won't do any work.
About the idea of making code modular, readable and maintainable: so business classes became cleaner, but all we did was shift confusion from dirty Java business classes to convoluted XML files and having to delete interfaces used to inject to our loosened objects.
In short, it seems we have to make edits and changes to a file somewhere,right?
Please feel free to put me in my place if my understanding is lacking, just a little irritated with learning Spring because I see the same amount of work just rearranged.
Dependency injection is good for unit testing because you can individually test each method without that method depending on anything else. That way each unit test can test exactly one method.
I would say that if the xml is what’s annoying you check out Spring boot. It’s based on a java configuration so no xml and it simplifies a lot of configuration for you based on your class path. When I first started spring I found the xml very daunting coming from a java background but the annotation based configuration and the auto configuring done by spring boot is extremely helpful for quickly getting applications working.
IMO biggest advantage of using the spring is dependency injection which makes your life easy. For example if you would like to create a new service with three dependencies, then you can create a class very easily using Spring. But without spring, you will end up writing different factory methods which will return you the instances you are looking for. This makes your code very verbose with static method calls. You may want to take a look at the code repositories before spring era.
Again if you would like to use Spring or not is your personal call based on project complexity. But it's other features/advantages cant be overlooked.
And XML files or Java configs are the ways of achieving spring configuration - where you would like to add your business logic is personal flavour. Only thing is you should be consistent all across your project.
I would suggest that you read Martin Fowler's great article on Inversion of Control and Dependency Injection to gain a better understanding of why frameworks like Spring can be really useful to solve a well known set of common dependency injection problems when writing software.
As others have mentioned, there is no obligation to use Spring; and whatever you can do with Spring, you can probably do it by other means like abstract factories, factory methods, or service locators.
If your project is small enough, then you probably wouldn't mind solving the dependency injection issues on your own using some design patterns like those mentioned above. However, depending on the size of your project, many would prefer to use a framework or a library that already packs a bunch of solutions to these recurrent head scratchers.
In regards to the advantages of dependency injection frameworks when doing unit testing is the idea that you don't need to test the dependencies of your class, but only your class.
For example, most likely your application has a layered design. It is very common to have a data access class or a repository that you use to retrieve data from a datasource. Logically, you also have a class where you use that DAO.
Evidently, you already wrote unit testing for your DAO, and therefore, when you're testing your business class (where the DAO is being used) you don't care about testing your DAO again.
Fortunately, since Spring requires some form of dependency injection for your DAO, this means your class must provide a constructor or a setter method through which we can inject that DAO into our business class, right?
Well, then during unit testing of your business class, you can conveniently use those injection points to inject your own fake DAO (i.e. a mock object). That way, you can focus on the testing of your business class and forget about retesting the DAO again.
Now compare this idea with other solutions you may have done on your own:
You inject the dependency directly by instantiating the DAO within your business class.
You use a static factory method within your code to gain access to the DAO.
You use a static method from a service locator within your code to gain access to the DAO.
None of these solutions would make your code easy to test because there is no simple manner to get in the way of choosing exactly what dependency I want injected into my business class while testing it (e.g. how do you change the static factory method to use a fake DAO for testing purposes?).
So, in Spring, using XML configuration or annotations, you can easily have different dependencies being injected into your service object based on a number of conditions. For example, you may have some configurations for testing that evidently would be different than those used in production. And if you have a staging environment, you may even have different XML configurations of dependencies for your application depending on whether it is running in production or integration environments.
This pluggability of dependencies is the key winning factor here in my opinion.
So, as I was saying, my suggestion to you is that you first expand your understanding of what problems Spring core (and in general all dependency injection frameworks) is trying to solve and why it matters, and that will give you a broader perspective and understanding of these problems in a way that you could to determine when it is a good idea to use Spring and when it is not.

Spring Annotations when java file is compiled

I started learning spring today and i have a question regarding what happens to the annotations when java files with annotations is compiled ?.
The reason i am asking this is because of the fundamental difference i see when we choose to use the xml approach vs the annotations approach , and what i think is the philosophy of spring. The way i understand is spring says that all your java classes can be simple pojo's and all the spring related config should be kept independent (Like xml file.)
In case of developing spring application using xml *.java files have no idea about spring container and are compiled in to .class without any spring related dependencies.
But now when we annotate the .java file and the file is compiled the compiled file now has all spring related dependencies hard baked in to it and no longer are your classes simple pojo's.
Is this correct ? I am not sure if i am missing some thing here.
Annotations can be considered as metadata of a class or its element (method, field, local variable...). When you put annotation, you don't implement any behaviour. You just give additional info on an element.
That way, Spring, which is in charge of instanciating its bean can collect the info with reflection (see also this site) and process it.
To conclude, your Spring beans still remain POJO and there is no difference with the XML way (...from that point of view) since Spring gets from annotations the information it would have got from XML .
I think you are right and your question is justifiable, that's the way how I think about it too.
Not only compiled code but also dependency on spring jars bother me. Once you use this annotations your resulting jar depends on spring library.
It's reasonable to store beans in model according to DDD but spring is some kind of infrastructure layer so I didn't like the dependency.
Even if you would use XML, it's useful for few placed to use attributes. E.g. #Required attribute which is useful to verify that linked bean was injected. So, I've decide to use constructor dependency injection to omit this attribute, see my article. I completely leave out the dependency on spring in the code.
You can probably find such mind hook for many annotation you want/force to use.
You can use annotations only for your configuration classes, without marking them actual bean classes. In such scenario if you not use spring you just not load configuration classes.

How to share bean INSTANCE across war in SPRING?

I want to share a singleton bean across multiple war. I know sharing ApplicaitonContext using parentContextKey attribute(Example, http://blog.springsource.org/2007/06/11/using-a-shared-parent-application-context-in-a-multi-war-spring-application/)
But this way instance of bean created multiple (for 2 war, 2 instance). I want only 1 instance across 2 war.
Another way, If i set some value in any POJO, it should be accessible in another war.
Reason i need this is, there are some beans(like HibernateSessionFactory, Datasource etc which are expensive) which are created multiple times(n instance for n war). Whereas i want to utilize same instance instead of creating same in different war.
Can anyone provide me solution for this?
You could achieve this by binding the objects into the global JNDI tree. That means that both WARs would have references to an object looked up in JNDI.
Hibernate allows you to use the hibernate.session_factory_name property (this may well be a good starting point. Data sources should already be looked up from JNDI.
One thing, I would not class a session factory or a data source as expensive, so you may well be saving a miniscule amount of memory in exchange for a lot of additional complexity, so I would ask myself the question on whether this is worth the additional maintenance headaches.
Spring provide a way to expose any bean (service) and these bean can be access from any other web application or any standalone application.
please refer Remoting and Web Service using Spring to get more details.

Spring core container is the basis for complete Spring framework?

All websites state that the Spring core container is the basis for complete Spring framework i.e., it is used across
the all modules like AOP, JDBC module, Web module, etc. As per my understanding, the Spring core container's main purpose is
to inject dependencies, so avoiding the need of factory classes and methods. Is that correct?
Second question: When it is said, Spring core container is the basis for complete Spring framework (e.g., for Spring AOP). As per my understanding, in Spring AOP also, getting the object of classes like
ProxyFactoryBean is achieved by core container. Right?
Thirdly, it is stated that Spring core container avoids the need for programming the use of singletons. How come singleton
classes are avoided by core container?
yep
yep
All beans declared in Spring config files are singleton by default. They are instantiated when your application starts.
First off, your understanding of what you get from Spring is about right. So let's get on to your third question, the interesting one.
The key is it's not that you don't have singletons, it's that they're singletons by configuration. This is a vital difference, as it means you can avoid all the complicated singleton enforcement code (the source of frequent problems) and instead just write exceptionally simple programs that focus on the business end of things. This is particularly important when you are writing a program with non-trivial object lifetimes: for example, in a webapp it makes it very easy to manage the lifespan of objects that hold state associated with a user's session, since if the objects have session scope, they'll be “singleton per user session”. That's enormously easier to work with than many of the alternatives.
The fact that Spring can also help out with transactions is just perfect as transaction handling is distinctly non-trivial, and AOP is the best solution to them in Java that I've seen (other languages have other options open) with Spring supporting a pretty straight-forward way of doing it. Try to do it properly without if you don't believe me. Spring's pretty much wonderful.

Resources