Multiple Bean Configurations of a Class - java

I have 2 beans configured for a class so that I can configure the class with two different data layer implementations. What I'm wondering is if there is a pattern or best practice for selecting between the two different beans in my code. I know without Spring, the Factory pattern would be commonly used for this, but it seems a bit redundant being as beans are retrieved from Spring via a factory.

There's no problem having a Factory within a Factory. It happens all the time in Spring, in fact. I'd say that sounds like a good approach here. Your data storage factory would be a Spring bean and be injected with the two different implementations, which are also beans. The job of the factory is to choose between them based on some input.

Declare both beans and mark one as primary. You can either use:
<bean primary="true" ...
in XML configuration or:
#Primary
#Bean
In #Configuration approach. Spring will prefer primary beans when performing autowiring. Reference documentation.

Related

Programmatically create spring beans for each bean/configuration/... of a given type

I would like to create programmatically a bunch of different beans for each bean (or configuration or similar) extending a given base class.
What makes it more difficult is, that the beans should be already available at the phase the autowiring of other beans takes place.
Is the some kind of spring base class or interface (something like BeanPostProcessor) I could implement to achive that?
Use case is similar to create a bean for each data source in context.

Spring 4 Dynamic Bean Creation

Maybe I'm not using the right terminology and that's why i can't find an answer, but I want to know how can I take information from a database to create beans that I can inject into the application?
Here's an example, rather than having this coded in a configuration file, I would like to possibly loop some values stored in a database and build these beans based on that:
#Bean
public CronTriggerFactoryBean cronTriggerFactoryBean() {
CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
factory.setJobDetail(jobDetailFactoryBean().getObject());
factory.setStartDelay(3000);
factory.setCronExpression("0 0/2 * 1/1 * ? *");
return factory;
}
How can I build beans like this and have them become a part of the application?
There are probably multiple ways how to achieve that, but all of them are pretty complex with a lots of pitfalls. I would say that in your example you should not create triggers as separate beans but rather have a single service to manage your schedules (and leave it out of Spring).
The thing with Spring is, that it is not designed to act as a dynamic container (like OSGi for example). This means that for example #Autowired dependencies are initialized during context startup and stays the same till the application context is destroyed.
However it is possible to construct bean definitions on the fly during initialization. Best place would be BeanFactoryPostProcessor. But this would be called during context initialization. This means you will have no other beans available (like EntityManager, DataSource, ...).
Another possibility is to somehow take advantage of context hierarchy. You can create and destroy application contexts on-the-fly. However implementing that would require deeper knowledge of Spring's internals.
Question for others: not sure if it is possible to reference initialized beans from parent context during child context initialization.
After you load the necessary bean properties from Database , use BeanDefinitionBuilder. You can refer this link

How to register an existing bean in Application context and what is the advantage I get out of it?

I am a newbie to Spring. I was going through spring documentation where it says we can register existing objects created outside spring container in application context. I did that like this
OutsideBean outsideBean = new OutsideBean();
ConfigurableApplicationContext applicationContext =
new ClassPathXmlApplicationContext("spring.xml");
// SpringBean is the bean which is defined in spring.xml
SpringBean springBean = applicationContext.getBean("springBean", SpringBean.class);
ConfigurableListableBeanFactory configurableListableBeanFactory =
applicationContext.getBeanFactory();
configurableListableBeanFactory.registerSingleton("outsideBean", outsideBean);
I have many unanswered questions here.
The way I am doing above, is it correct.?
Even if it is correct, is it the best way to do that.?
What if I have to register a bean as a 'prototype'.?
By registering my bean in application context what is the advantage I get out of it.?
I read through many links in stackoverflow but couldnt understand it. Hence asking it in new thread.
AFAIK, yes
No, it's not the best way. The best way is to create the context from a Spring configuration class, and to create beans in this configuration class, using #Bean annotated methods, as described in the documentation. Or simply by annotating your class with #Component and letting Spring find your bean by classpath scanning.
Your specify a scope using the #Scope annotation
The advantage is that the bean is managed by Spring, and can thus be injected by Spring in all the other beans. It can also be injected by any other bean. And it can benefit from AOP in order, for example, to provide transactional methods.
Well prasad, to understand what is applicationcontext / bean / what will you get out of it you need to go through the basic architecture of Spring framework, Spring literally stands out when compared other java frameworks, as its DI (Dependency Injection) & IOC (Inversion of control) container features.
Rod Johnson laid the foundation for Spring in his Expert One-on-One J2EE Design and Development (http://as.wiley.com/WileyCDA/WileyTitle/productCd-0764543857.html) way back in 2002. Which suggested framework specific free POJO's power to enhance modern enterprise application developement.
Kindly go through foll. link, to know about DI & IOC.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/overview.html
TO answer your questions.
The way I am doing above, is it correct
Well technically what you did will work definitely. But Spring provides no. of combination to define a object as a bean.
Even if it is correct, is it the best way to do that.?
I suggest you define all your beans in XML document or annotate the class which u want as a bean with #Component annotation or you can omit XML file do away everything with Java configuration file (which i have not really tried).
What if I have to register a bean as a 'prototype'.?
Can you please elaborate what u mean by Prototype
By registering my bean in application context what is the advantage I get out of it.?
If you understand the essence of DI u will easily answer this question by yourself. As mentioned earlier for DI spring provides IOC factory called BeanFactory (its an interface go thorough docs, there are many implementation BeanFactory, ApplicationContext is one of them). So if you configure a object as a bean u can ask factory to give to u at any no of times with its properties are again loosely coupled with one or more beans in container.

Adding behaviour using Spring

I have a bunch of projects which declare some spring bean files. I would like to write a "library" which supplies a utility which takes some bean names and adds some behaviour "around" the objects (example: Call Counting, Monitoring, Logging etc)
One obvious way for doing this would be to add some AspectJ annotations in the spring xml files in the projects but I would like the "utility" to search for some beans and add behaviour to them (This way the projects themselves are not aware of the utility).
The utility will be declared in the spring xml file somewhere so it has access to the ApplicationContext as it could implement ApplicationContextAware interface however I am keen on exploring how one would go about modifying behaviour of another bean in the app context programmatically. ex, something like find a bean of id "OrderService", create an aspected bean with some monitoring/call counting etc around all methods and replace that bean in the application context for "OrderService"
I know there are disadvantages with this approach but what I am after is "IS it possible to do this? And if yes how?"
If you don't want to use AOP, you can achieve this using a BeanPostProcessor. The Spring documentation states:
The BeanPostProcessor interface defines callback methods that you can
implement to provide your own (or override the container's default)
instantiation logic, dependency-resolution logic, and so forth. If you
want to implement some custom logic after the Spring container
finishes instantiating, configuring, and otherwise initializing a
bean, you can plug in one or more BeanPostProcessor implementations.
So you may create and register a BeanPostProcessor and implement the postProcessAfterInitialization(Object bean, String beanName) method to modify the methods you want to customize. Here is an example.
(But I would still recommend that you do this with AOP as this is the classical use case for it and it's much easier and more declarative. With the bean() pointcut, you can even advise beans with names matching a certain pattern.)
You can create your own BeanPostProcessor. You just have two declare it in applicationContext.xml and it will be called for each bean during initialization of beans (in fact, just before or just after). In each call you get a the actual object and its name. There, you can, for example, wrap that object depending on its name or type.

How is dependency injection working?

I am reading the Pro Spring 2.5 book and I have a question to how dependency injection works.
I understand the BeanFactory and doing dependency lookups. Now I read about dependency injection and I have some questions. Based on what I understand you want to limit the lookups to the minimum such as looking up an object for boot strapping the application. Then dependency injection will take care of the rest. However I don't understand this works.
Let say you have a beanfactory, you get an MyApplication instance that starts the whole application. The rest of the objects use dependency injection to get their collaborators. The beanfactory maintains the list of beans it manages but isn't this factory only available in the main method of the application? And if the beanfactory also manages the scope of their containing beans I don't understand how that is done. Are the beanfactory global in some way?
The bean factory instantiates all objects. It parses your configuration (xml or annotations), instantiates your beans and sets their dependencies. Then all these beans are stored in the application context.
You usually have an entry point to your application - there you do context.getBean(..). Now that bean has its dependencies injected, because it is put in the context by the bean factory.
The rule of thumb that will probably clear things: you never use the new operator (with bean classes) when using a DI framework. The framework makes the instances, not you.
So, there are two ways this can happen (as of Spring 3). In "traditional" dependency injection, the bean factory can only inject dependencies into beans it creates itself. In this scenario, the bean factory will resolve and inject all dependencies of a bean when that bean is first created.
The other way requires you to employ "full" AspectJ with either load- or compile-time weaving. In this scenario, you use an aspect in the spring-aspects.jar that basically pointcuts all new operations, allowing you to get dependency injection in arbitrarily created objects. This is triggered by using the #Configurable annotation. You can read more here.
The whole point on inversion of control and dependency injection is that you (typically) don't need the beanfactory except to get your application started. Your dependencies "automatically appear" in your objects. This is basically intended for objects with very few, typically one, instance during the whole lifetime of your application.
E.g. if your MyApplication depends on an instance of MyModuleA, you can simply have it #Autowired. When you fetch the application object from beanfactory at start time it already comes with an instance of MyModuleA preset.
About the scopes: this comes from web context. Besides objects with only one instance ever you can have objects scoped to a user's session. There you can store information you need to keep over several requests but separate for different users, think: shopping cart.
Typically treat the bean factory as global. I think it would be possible to have several instances, but they would be disconnected and can't inject objects only known to other instances.

Categories