Spring vs hibernate object creation - spring

I recently learnt that in hibernate, we need a no-arg constructor in an entity because hibernate instantiates its entities via reflection:
Hibernate implementation. Are we paying the reflection penalty?
I got curious that whether it is the same case with Spring and found that Spring beans do not require a no-argument constructor mandatorily.
This brings me to the question that how does spring creates its objects if not by reflection - to which I think that Spring is a container and instantiates beans and injects dependencies on startup and it must be able to load the application beans via some classloader and hence it does not need reflection.
Then, I get back to the starting point with the question that hibernate also has my application class definition available then why does it need reflection to create its entities?
can somebody please confirm or correct my understanding and provide me an answer?

Related

Spring managed vs non-managed beans

I have a simple Result data holder object that gets returned from a method.
I'm confused on what the right way of using or creating this object using Spring boot.
Should this class be marked with #Component annotation?
Can I just create this object using 'new Result()' or should I autowire and use it?
If I use 'new Result()' then this instance will not be managed by Spring. Is that understanding correct? What are the advantages or disadvantages of managed vs non-managed beans.
Thanks,
Sudha
If I use 'new Result()' then this instance will not be managed by Spring. Is that understanding correct? What are the advantages or disadvantages of managed vs non-managed beans.
Well the greatest difference is the Inversion Of Control IoC (aka Dependency Injection DI). If Result is managed by spring, you can autowire other spring beans (like services, components, repositories and so on) Moreover you can autowire the Result bean in other spring beans. More details can be found here
Can I just create this object using 'new Result()' or should I autowire and use it?
Well it depends on your scenario. For example if you have a JSON response in a Spring controller, well in this case it's better to use a classic POJO and create it because it depends on your business logic.
On the other side id your bean is a kind of service who can be used in other points of your project because it offers some methods, well in this case I guess it's good to autowire it and make it as a spring bean
Should this class be marked with #Component annotation?
Well as I said earlier it depends on your scenario. In the case you described (result of a method) maybe it's better to use a classical POJO. But you didn't provide enough information

Which is better to implement a singleton in a Spring application: a bean or a static field?

I am developing Spring MVC app, i need to implement singleton pattern for some kind of utilities, ex: imageuploader and others.
My question is: in what way to implement singleton for this utilities, to initialize beans for these classes and inject where i need like Controllers, Services, DAO?, or to use static field implementation of singleton to keep instance of this class?
First, try to avoid singleton as it's considered to be a bad practice. Also their interactions with other instances are difficult to test and validate, compared to non-singleton instances.
If you absolutely need it, I'd suggest you use a Spring bean so you can exploit the autowiring mechanism and Spring's bean lifecycle.
See the Beans section of the Spring reference doc for more info.
Using a Spring bean as will allow you to easily inject a mock in unit tests. However, you will only be able to access it from other Spring beans (or objects created by Spring beans that pass in a reference to it).
Also see this discussion in this question: Difference between static class and singleton pattern?
Traditionally, you'd use PropertyPlaceholderConfigurer to inject config from properties files into a Spring web-app. This blog discusses a variety of newer ways to do this with Spring.

Getting Spring object instantiation right

I'm new to Spring and a little confused about how it works. I get that I can use the application context to instantiate beans and have them populated. However, is the idea that I should be able to just write Bean b = new Bean() and then have Spring to somehow automagically populate that Bean?
I'm experimenting with Spring in a web application, and as far as I can see I need to inject the ApplicationContext into, say, the servlets to be able to instantiate other beans (services, daos etc.) from there. It's a bit cumbersome, but probably works.
However, is Spring meant to be able to hook into any object instantiation which happens on classes defined as beans in applicationContext.xml?
Spring is an Inversion of Control container. A bean is an object whose life cycle is managed by Spring. If you want Spring to populate an object, it needs to go through Spring, ie. it needs to be bean.
is Spring meant to be able to hook into any object instantiation
which happens on classes defined as beans in applicationContext.xml?
Spring doesn't hook into anything. You configure your beans and the relationships between them with Spring and Spring handles creating the instances and linking them up.
For domain objects, Spring provides a solution via the #Configurable annotation: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-atconfigurable
It requires compile- or load-time-weaving and, thus, introduces some additional complexity but having the convenience of using the standard new Bean() syntax plus Spring's autowiring is worth it in my opinion.
Alternatively, you could define your domain objects as beans with prototype scope and use some factory to create them using the Spring ApplicationContext.getBean() method. With a scope of prototype a new instance will be returned every time and since you go through the ApplicationContext, Spring will do all the dependency injection magic as usual.
As for services and other beans with singleton scope, you would typically NOT retrieve them by first injecting the ApplicationContext and using it but instead you would inject them via either a constructor, setter or annotation-based strategy. The documentation covers that in detail: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-collaborators

Use/Purpose of beans in Spring

Could someone give an overview or a summary of what the purpose of beans in a Spring framework context?
I understand the standard Java bean (no arg constructor, getters/setters, often serialized), but the Spring bean purpose seems to be different.
Is it a way of implementing the Singleton design pattern (one instance, for like factory classes) in a simple, reusable fashion?
I've mainly used Spring with annotations, but I feel I need to grasp this in order to understand Spring.
Thanks!
Beans are objects that form the backbone of the application.
A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container; other than that, there is nothing special about a bean.It is in all other respects one of probably many objects in your application.
Spring beans are defined in a spring configuration file or by using annotations, instantiated by the Spring container, and then injected into your application.
Spring beans will not be singleton design pattern until you explicitly make them to be.The singleton design pattern and the spring scope 'singleton' are different things.You can define different bean scopes depending on your requirements.
The scopes could be :
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP
session.
The default scope is singleton.
I understand the standard Java bean (no arg constructor,
getters/setters, often serialized), but the Spring bean purpose seems
to be different.
You mean always serialized. Why do you think the purpose seems different?
In the end, you write classes. A lot of time these are POJOs, Plain Old Java Objects. Sometimes you implement an interface or extend a class, but its all just classes.
Beans are just classes. Don't overcomplicate it.
Now Spring might take your beans (classes) and manage them for you via any of a number of policies (prototype, singleton) but that doesn't change what a bean is, it speaks to how Spring manages the bean.
To understand best, you should get familiar with dependency injection. In a few words dependency injection allows you to use objects, or services without explicitly creating them (of course, it gives other benefits, but let's focus on the question). This is achieved by maintaining a dependency container that is - roughly said - a collection of beans.
A bean is a service/component you use in your application. Unlike the EJB, with Spring the bean is not constrained to constructor arguments or specific annotations (especially if you use xml contexts). You register a bean with a container (by defining a context), and when you require it, the container will provide you with an instance of that bean. In order to create the bean, the container examines its class and constructors, and uses any other registered beans within that context, to call the appropriate constructor or property setter.
You can configure a bean to be a singleton - this is not a singleton as in the design pattern term. Singleton beans are created once within the container, and the same instance is used whenever the bean is requested from that container. You can also use the prototype scope to force the container to create a new instance each time.

hibernate validator without using autowire

I'am currently working on a Jersey project and decided to use Hibernate validator for the parameter validations. All dependencies injected on the Endpoint classes are properly initialized. However for those dependencies in the ConstraintValidator classes, it always throw a NPE. So i followed the guide on Spring+hibernate guide and registered
bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
and used the #Autowired annotation for the services in the ConstraintValidator class which needs to be injected.
are there side effects of using it? Is there a way to avoid the autowiring annotation in ConstraintValidator class and still injecting the values? I tried manually registering the constraintValidator class in the context as bean, adding a property reference to the service that i need, however it throws a null pointer exception.
"Hibernate Validator - JSR 303 Reference Implementation - Reference Guide" says something about portality:
Warning
Any constraint implementation relying on ConstraintValidatorFactory
behaviors specific to an implementation (dependency injection, no no-arg
constructor and so on) are not considered portable.
So, is it a bad thing? In my opinion it's not. Of course you are now coupled to the DI container (Spring) and can't easily reuse validators (e.g. when not using Spring). On the other hand, with your validators build by a Spring factory you can take full advantage of the framework and do very heavy lifting (read revision data for entities and comparison of previous states, call arbitrary services, enhance or localize validation messages, ...).
One thing you must be very careful about is that a validator's semantics is normally read-only and should not cause side-effects by calling it. For example don't accidentally flush data to the database because of some auto-flushing by invoking a (transactional) service or reading data inside your validator.

Resources