How to specify parent for bean in Spring annotation config? - java

How to specify a parent for bean in Spring annotation config?
BaseDao "baseDao" bean should be the parent for
#Configuration
public class CategoryContext {
#Bean
#Scope("prototype")
public CategorySqlHibernateDAO categorySqlHibernateDAO() {
return new CategorySqlHibernateDAO();
}
}
Or Spring 4.2.5 automatically will do this?

Inheritance is sufficient. No need to define anything extra.
CategorySqlHibernateDAO should extend BaseDao.
Regarding your last comment, abstract classes don't need any further annotations or definitions - Just the concrete classes that extend them.
You can define Configuraions class which would be abstract with any fields/methods/abstract methods you want, and than when you extend this class put the required annotations in it. Hope this helps...

Related

Can I extend an #Component and create another #Component class and make only one available at a time?

I have a library jar which I want to provide to a number of applications. The behavior I want is to create a common spring component class in the library. If in the applications, the same component is not extended then use the common component; if it's extended in the app, then use the extended component (child class). Is this possible? - Create CommonComponent only if a child for that class doesn't exist.
I am using Java 1.8, Springboot2.0
Created class in library:
#Component
public class CommonComponent{}
In one of the child apps using the library, I added a child component:
#Component
public class ChildComponent extends CommonComponent{}
I expected one component ChildComponent created; but in the above scenario 2 components - CommonComponent and ChildComponent are created.
One way you could do this is to take advantage of the #ConditionalOnMissingBean annotation that Spring Boot has. When combined with a bean definition in a #Configuration class, we can tell Spring to only define our bean if it doesn't already have one.
This is untested:
#Configuration
public class CustomComponentConfiguration {
#ConditionalOnMissingBean(CustomComponent.class)
#Bean
public CustomComponent customComponent() {
return new CustomComponent();
}
}
In this example, when our #Configuration runs, Spring determines if there is any other bean that is a CustomComponent. If not, it executes the customComponent() method and defines whatever bean you return. So if somebody else defines a ChildComponent, this method will not get called.
when you are creating the child component put #Primary annotation
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency
so you'll have
#Primary
#Component
public class ChildComponent extends CommonComponent { /* ... */ }
and in your services autowire CommonComponent type and spring will inject ChildComponent or CommonComponent

Spring. Class loader

I have the following problem.
It is necessary for me that the classes implementing the certain interface automatically became beans(like with #Component).
For example, I have package com.test with context:component-scan base-package="com.test" that has two classes. One of them has annotation #Component, but other only implements specific interface.
I need a class with this interface to become a bean as well as a class with an annotation.
How can i do this?
You can add annotation #Component or #Service to your class and it wil be bean or you could add you class as #Bean to your spring configuration
You can use reflection to access all classes implementing a given interface and then add them manually to your context but please don't.
Just add #Component (and #Qualifier("beanName") if you have more than one bean implementing this interface)
There are multiple ways to achieve this
Add Spring Stereotype #Componenet, #Serivce, #Repository etc. based on your type of class
Explicitly define the Bean in your configurations
#Bean
public InterfaceType methodname(){
return new Implementation();
}
Programmatically using org.springframework.beans.factory.config.ConfigurableBeanFactory
#Configuration
#DependsOn("ContextProvider") //Not sure whether we need this
public class BeanConfig implements BeanFactoryAware {
private BeanFactory beanFactory;
#SuppressWarnings({ "rawtypes" })
private void createBean() throws Exception{
if(null == beanFactory){
throw new Exception("Couldnot load Bean Factory");
}
ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
configurableBeanFactory.registerSingleton("name", implementation);;
}
}
If you have multiple implementations of an interface then please provide a name with Bean or Stereotype Annotations and use that name while Autowiring.

Interfaces are annotated with #Component annotation in spring IoC/DI. What could be the reason?

Some times interfaces are annotated with #Component annotation. Then my obvious reasoning was that classes that implement such interface will be treated as components as well. But if I am right that is not the case.
So what is the purpose of #Component annotation on interfaces.
Annotating an interface with #Component is common for Spring classes, particularly for some Spring stereotype annotations :
package org.springframework.stereotype;
...
#Component
public #interface Service {...}
or :
package org.springframework.boot.test.context;
...
#Component
public #interface TestComponent {...}
#Component is not declared as an inherited annotation :
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Documented
public #interface Component {...}
But whatever, during loading of the context, Spring discovers beans by considering the hierarchy of the annotation declared in the candidate class.
In the org.springframework.boot.BeanDefinitionLoader class (included in the Spring Boot dependency) that loads bean definitions from underlying sources, you can see an example of
org.springframework.core.annotation.AnnotationUtils.findAnnotation() that Spring uses to retrieve annotations in the whole hierarchy of the annotation:
class BeanDefinitionLoader {
...
private boolean isComponent(Class<?> type) {
// This has to be a bit of a guess. The only way to be sure that this type is
// eligible is to make a bean definition out of it and try to instantiate it.
if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
return true;
}
// Nested anonymous classes are not eligible for registration, nor are groovy
// closures
if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
|| type.getConstructors() == null || type.getConstructors().length == 0) {
return false;
}
return true;
}
...
}
Concretely, it means as the #Service annotation is itself annotated with #Component, Spring will consider a candidate class annotated with #Service as a bean to instantiate.
So, your guesswork is right :
Classes that implement such interface will be treated as components as
well.
But this works only for interfaces (such as #Service) that are Java annotations and not for plain interfaces.
For Spring classes, this way of doing makes sense (enriching actual stereotype for example) but for your own beans, using #Component for the interface rather than the implementation will not work and would bring more drawbacks than advantages :
it defeats in a same way the purpose of an interface that is above all a contract. It couples it to Spring and it supposes that you will always have a single implementation of the class. In this case, why using an interface ?
it scatters the reading of the class at two places while the interface doesn't need to have any Spring stereotype.
That is not the case there is no need to adding #component on an interface because it is not a bean as we can't create reference for it.
The main part is actually #autowired where you injection the dependecy.
For example
public interface SortAlog();
public class BubbleSortAlgo();
No we are following the dynamic binding and creating the object of interface but implementation is on the run time.
So #autowired is the one that will create the object internally and we have #component for bubbleSortAlgo and the only candidate for the injection, so it will get reference from there.
I hope I was able to make a point here.

Hibernate Annoration: how to get the bean of class annotated as #Repository

I am writing a persistence layer code using hibernate.
I have soem DAO classes which I used to annotated as #Component.
package com.mycompany.mypackage;
#Component
class MyDAO {
}
I use component scan in my Spring configuration like this:
<context:annotation-config/>
<context:component-scan base-package="com.mycompany.mypackage"/>
If I do so, a bean with id "myDAO" is created. However, I was told that it is better to use #Repository as it is a persistence layer code.
But after I replaced #Component with #Repository, the beans a not automatically created.
My questions are that: What is the difference between these two annodations? How can I create bean with auto scan and using #Repository? If I keep using #Component, will that work?
Thanks a lot.
#Repository beans are eligible for persistence exception translation and the should be loaded at runtime. This is what you want to use for your DAO layer.
#Component was added to Spring later and just means that the annontated class is a "spring bean" and will be loaded with during a component scan.
Generic DAOs don't mesh well with component scanning. This makes sense if you think about it - you need to be able to define multiple instances of this class, differing by the class passed into the constructor only. The class itself isn't capable of being autowired, so Spring can't do anything with it.
For this part, your best bet is to just define the repo instances in XML. If you're really determined to use component-scanning, you'll have to subclass the Generic DAO and provide a default constructor that hardcodes the class
As #Mortsahl says, just do something like the following
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
private Class<T> type;
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public GenericDAOImpl(){
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class<T>) pt.getActualTypeArguments()[0];
}
This way you can extend out your generic DAO and still be eligible for autowiring.

Spring: #Component versus #Bean

I understand that #Component annotation was introduced in spring 2.5 in order to get rid of xml bean definition by using classpath scanning.
#Bean was introduced in spring 3.0 and can be used with #Configuration in order to fully get rid of xml file and use java config instead.
Would it have been possible to re-use the #Component annotation instead of introducing #Bean annotation? My understanding is that the final goal is to create beans in both cases.
#Component
Preferable for component scanning and automatic wiring.
When should you use #Bean?
Sometimes automatic configuration is not an option. When? Let's imagine that you want to wire components from 3rd-party libraries (you don't have the source code so you can't annotate its classes with #Component), so automatic configuration is not possible.
The #Bean annotation returns an object that spring should register as bean in application context. The body of the method bears the logic responsible for creating the instance.
#Component and #Bean do two quite different things, and shouldn't be confused.
#Component (and #Service and #Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.
#Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.
To answer your question...
would it have been possible to re-use the #Component annotation instead of introducing #Bean annotation?
Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.
#Component auto detects and configures the beans using classpath scanning whereas #Bean explicitly declares a single bean, rather than letting Spring do it automatically.
#Component does not decouple the declaration of the bean from the class definition where as #Bean decouples the declaration of the bean from the class definition.
#Component is a class level annotation whereas #Bean is a method level annotation and name of the method serves as the bean name.
#Component need not to be used with the #Configuration annotation where as #Bean annotation has to be used within the class which is annotated with #Configuration.
We cannot create a bean of a class using #Component, if the class is outside spring container whereas we can create a bean of a class using #Bean even if the class is present outside the spring container.
#Component has different specializations like #Controller, #Repository and #Service whereas #Bean has no specializations.
Let's consider I want specific implementation depending on some dynamic state.
#Bean is perfect for that case.
#Bean
#Scope("prototype")
public SomeService someService() {
switch (state) {
case 1:
return new Impl1();
case 2:
return new Impl2();
case 3:
return new Impl3();
default:
return new Impl();
}
}
However there is no way to do that with #Component.
Both approaches aim to register target type in Spring container.
The difference is that #Bean is applicable to methods, whereas #Component is applicable to types.
Therefore when you use #Bean annotation you control instance creation logic in method's body (see example above). With #Component annotation you cannot.
I see a lot of answers and almost everywhere it's mentioned #Component is for autowiring where component is scanned, and #Bean is exactly declaring that bean to be used differently. Let me show how it's different.
#Bean
First it's a method level annotation.
Second you generally use it to configure beans in Java code (if you are not using xml configuration) and then call it from a class using the
ApplicationContext.getBean method. Example:
#Configuration
class MyConfiguration{
#Bean
public User getUser() {
return new User();
}
}
class User{
}
// Getting Bean
User user = applicationContext.getBean("getUser");
#Component
It is the general way to annotate a bean and not a specialized bean.
It is a class level annotation and is used to avoid all that configuration stuff through java or xml configuration.
We get something like this.
#Component
class User {
}
// to get Bean
#Autowired
User user;
That's it. It was just introduced to avoid all the configuration steps to instantiate and use that bean.
You can use #Bean to make an existing third-party class available to your Spring framework application context.
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
By using the #Bean annotation, you can wrap a third-party class (it may not have #Component and it may not use Spring), as a Spring bean. And then once it is wrapped using #Bean, it is as a singleton object and available in your Spring framework application context. You can now easily share/reuse this bean in your app using dependency injection and #Autowired.
So think of the #Bean annotation is a wrapper/adapter for third-party classes. You want to make the third-party classes available to your Spring framework application context.
By using #Bean in the code above, I'm explicitly declare a single bean because inside of the method, I'm explicitly creating the object using the new keyword. I'm also manually calling setter methods of the given class. So I can change the value of the prefix field. So this manual work is referred to as explicit creation. If I use the #Component for the same class, the bean registered in the Spring container will have default value for the prefix field.
On the other hand, when we annotate a class with #Component, no need for us to manually use the new keyword. It is handled automatically by Spring.
When you use the #Component tag, it's the same as having a POJO (Plain Old Java Object) with a vanilla bean declaration method (annotated with #Bean). For example, the following method 1 and 2 will give the same result.
Method 1
#Component
public class SomeClass {
private int number;
public SomeClass(Integer theNumber){
this.number = theNumber.intValue();
}
public int getNumber(){
return this.number;
}
}
with a bean for 'theNumber':
#Bean
Integer theNumber(){
return new Integer(3456);
}
Method 2
//Note: no #Component tag
public class SomeClass {
private int number;
public SomeClass(Integer theNumber){
this.number = theNumber.intValue();
}
public int getNumber(){
return this.number;
}
}
with the beans for both:
#Bean
Integer theNumber(){
return new Integer(3456);
}
#Bean
SomeClass someClass(Integer theNumber){
return new SomeClass(theNumber);
}
Method 2 allows you to keep bean declarations together, it's a bit more flexible etc. You may even want to add another non-vanilla SomeClass bean like the following:
#Bean
SomeClass strawberryClass(){
return new SomeClass(new Integer(1));
}
You have two ways to generate beans.
One is to create a class with an annotation #Component.
The other is to create a method and annotate it with #Bean. For those classes containing method with #Bean should be annotated with #Configuration
Once you run your spring project, the class with a #ComponentScan annotation would scan every class with #Component on it, and restore the instance of this class to the Ioc Container. Another thing the #ComponentScan would do is running the methods with #Bean on it and restore the return object to the Ioc Container as a bean.
So when you need to decide which kind of beans you want to create depending upon current states, you need to use #Bean. You can write the logic and return the object you want.
Another thing worth to mention is the name of the method with #Bean is the default name of bean.
Difference between Bean and Component:
#component and its specializations(#Controller, #service, #repository) allow for auto-detection
using classpath scanning. If we see component class like #Controller, #service, #repository will be scan automatically by the spring framework using the component scan.
#Bean on the other hand can only be used to explicitly declare a single bean in a configuration class.
#Bean used to explicitly declare a single bean, rather than letting spring do it automatically. Its make septate declaration of bean from the class definition.
In short #Controller, #service, #repository are for auto-detection and #Bean to create seprate bean from class
- #Controller
public class LoginController
{ --code-- }
- #Configuration
public class AppConfig {
#Bean
public SessionFactory sessionFactory()
{--code-- }
Spring supports multiple types annotations such as #Component, #Service, #Repository. All theses can be found under the org.springframework.stereotype package.
#Bean can be found under the org.springframework.context.annotation package.
When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using #ComponentScan) each class and inject the instance of the classes to the IOC container. Another thing the #ComponentScan would do is running the methods with #Bean on it and restore the return object to the Ioc Container as a bean.
#Component
If we mark a class with #Component or one of the other Stereotype annotations these classes will be auto-detected using classpath scanning. As long as these classes are in under our base package or Spring is aware of another package to scan, a new bean will be created for each of these classes.
package com.beanvscomponent.controller;
import org.springframework.stereotype.Controller;
#Controller
public class HomeController {
public String home(){
return "Hello, World!";
}
}
There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach since it's purely declarative. It is also important to note that the stereotype annotations are class level annotations.
#Bean
#Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically like we did with #Controller. It decouples the declaration of the bean from the class definition and lets you create and configure beans exactly how you choose. With #Bean you aren't placing this annotation at the class level. If you tried to do that you would get an invalid type error. The #Bean documentation defines it as:
Indicates that a method produces a bean to be managed by the Spring container.
Typically, #Bean methods are declared within #Configuration classes.We have a user class that we needed to instantiate and then create a bean using that instance. This is where I said earlier that we have a little more control over how the bean is defined.
package com.beanvscomponent;
public class User {
private String first;
private String last;
public User(String first, String last) {
this.first = first;
this.last = last;
}
}
As i mentioned earlier #Bean methods should be declared within #Configuration classes.
package com.beanvscomponent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class ApplicationConfig {
#Bean
public User superUser() {
return new User("Partho","Bappy");
}
}
The name of the method is actually going to be the name of our bean. If we pull up the /beans endpoint in the actuator we can see the bean defined.
{
"beans": "superUser",
"aliases": [],
"scope": "singleton",
"type": "com.beanvscomponent.User",
"resource": "class path resource
[com/beanvscomponent/ApplicationConfig.class]",
"dependencies": []
}
#Component vs #Bean
I hope that cleared up some things on when to use #Component and when to use #Bean. It can be a little confusing but as you start to write more applications it will become pretty natural.
#Bean was created to avoid coupling Spring and your business rules in compile time. It means you can reuse your business rules in other frameworks like PlayFramework or JEE.
Moreover, you have total control on how create beans, where it is not enough the default Spring instantation.
I wrote a post talking about it.
https://coderstower.com/2019/04/23/factory-methods-decoupling-ioc-container-abstraction/
1. About #Component
#Component functs similarily to #Configuration.
They both indicate that the annotated class has one or more beans need to be registered to Spring-IOC-Container.
The class annotated by #Component, we call it Component of Spring. It is a concept that contains several beans.
Component class needs to be auto-scanned by Spring for registering those beans of the component class.
2. About #Bean
#Bean is used to annotate the method of component-class(as mentioned above). It indicate the instance retured by the annotated method needs to be registered to Spring-IOC-Container.
3. Conclusion
The difference between them two is relatively obivious, they are used in different circumstances.
The general usage is:
// #Configuration is implemented by #Component
#Configuration
public ComponentClass {
#Bean
public FirstBean FirstBeanMethod() {
return new FirstBean();
}
#Bean
public SecondBean SecondBeanMethod() {
return new SecondBean();
}
}
Additional Points from above answers
Let’s say we got a module which is shared in multiple apps and it contains a few services. Not all are needed for each app.
If use #Component on those service classes and the component scan in the application,
we might end up detecting more beans than necessary
In this case, you either had to adjust the filtering of the component scan or provide the configuration that even the unused beans can run. Otherwise, the application context won’t start.
In this case, it is better to work with #Bean annotation and only instantiate those beans,
which are required individually in each app
So, essentially, use #Bean for adding third-party classes to the context. And #Component if it is just inside your single application.
#Bean can be scoped and #component cannot
such as
#Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)

Categories

Resources