Beans inside beans in SpringFramework? - java

There are some situations, where beans can be regarded as entities, similar to bean containers or configurations.
For example, GUI window can contain some controls. Here, both windows and it's controls are beans.
Does SpringFramework provide some specific patterns to implement this situation? For example, may be it is ok to implement BeanFactory or use #Component annotation for this?
Or the main guidance is still initialize everything from separate configuation and not mix it with real objects?

I cannot get your point clearly but what I understood is you are trying to have a bean inside a bean. If I understood correctly the you can use the annotation #Bean over a component inside any bean class which is decorated with any of the following annotation - #Controller, #RestController, #Configuration, #Repository, #Service, #Component.
A method onto which you decorate #Bean should return an object that can qualify to register as a bean.
Now you can inject (using #Autowired) this registered bean.

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.

Use class annotation to run on class initialization with Spring AOP

Is it possible to create a Java aspect that runs on class initialization using Spring AOP?
We have an annotation that will be used in several places, and in order to make use of the annotation we need some boilerplate code that needs to run every second (using #Scheduled). We're hoping to move that boilerplate code to another class-level annotation to make it easier to reuse.
As far as I understand, it's not possible to implement such a class-level annotation using Spring AOP since it only supports method execution (https://www.baeldung.com/spring-aop-vs-aspectj#4-joinpoints). Is there any workaround to achieve what we're hoping for? I'm aware we could use AspectJ instead of Spring AOP, but I'm reluctant to do that because it's complex to use.
Code snipped:
#Scheduled(fixedDelayString = "${app.pollable-consumer.time-interval}")
public void pollForDeletionRequest() {
log.trace("Polling for new messages");
cleanupInput.poll(cleanupSubmissionService::submitDeletion);
}
Thanks for your help.
Update: The annotation needs to be added to a library to enable it to be shared by different microservices.
We think that writing a new class-level annotation might help. It would run on class initialization, find all methods that are annotated with #PollableStreamListener, and schedule the polling to happen for each of the Kafka topics.
To slightly adjust the terminology and shift the focus, is it acceptable to bind the creation of such a construction to Spring's Application Context initialization? If so, you could create a Bean Factory Post Processor that would have been triggered for each #PollableStreamListener.
In a nutshell, BFPP runs before spring creates the beans during the application context initialization. This mechanism allows to "dynamically" create beans that in a runtime will be indistinguishable from those created by spring in a regular way, a kind of hook to the spring initialization lifecycle that you can use here.
So this BFPP and introspect the methods of your interest. Then based on the information found in the annotations / configuration This BFPP could register a Bean Definition per scheduled job of the bean (a class with all the required parameters that you could prepare as a part of the infrastructure). Then spring will read this bean definition and create the beans out of this bean definition as it usually does.
Here you can find an example of how to use this BFPP and more specifically its registerBeanDefintion method.

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.

Declare my own annotaion

As you know when I want to inject a class to my class's property in spring framework I do something like this:
Class sample {
#Autowired
MyService service;
}
or use #Resource or #Named or what else.
but now I wonder that if possible I declare my own annotation like #MyInjection to do this stuff and besides do something more.
for example, instead of searching the application context and find proper bean to inject, create a class and inject this created bean to property of class.
Thanks.
An annotation is just basically data about data. So if you want something to handle your annotation you have to write a custom annotation processor.
I suggest you should look into Spring's AOP features for more details:
Aspect Oriented Programming with Spring
With AOP you basically create an annotation (in your case) then you configure Spring to do something when it bumps into your annotation (Spring uses regexps for this if I remember it right). This is called a Pointcut. Then if Spring finds a match it runs your custom code which can be basically anything.
I think what you want could be achieved by using Spring's factory method, which gets called when Spring is about to resolve some dependency. See example Hope this helps.

Multiple Bean Configurations of a Class

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.

Categories