getting bean id of target class in advice - spring

I have a few classes that interact with databases (more than one). Some classes are reused so for example "obs.table1" is used to interact with table1 in database "obs" while "ref.table1" is used to interact with table1 in database "ref". These databases are at different URLs and each gets its own connection pool, etc... obs.table1 and ref.table1 are both instances of MyTable1Class, defined in beans file.
I have a pointcut that intercepts calls to methods annotated with #Transactional or with a custom annotation #MyTablesAnnotation and have it set so those calls will all get routed into a #Around advice.
This all works and the flow through the advice is correct.
What I am trying to add is reporting on what is going on in there. Currently I can tell where in there I am, but I can't tell if it was obs.table1 or ref.table1 object that got me there.
Is there a way to extract the bean id of the object on whose method the advice was invoked on?
ProceedingJoinPoint that is passed to the method the only thing I do with it is call a .proceed on it and the rest is just various checks and catches. I see that I can get either the target class or proxy class out of it, but... not sure how to go from there to knowing what the bean id was.
Is it possible?

Firstly it is not recommended to depend on bean id as it creates tight coupling with framework.
To quote from docs Note that it is not usually recommended that an object depend on its bean name, as this represents a potentially brittle dependence on external configuration, as well as a possibly unnecessary dependence on a Spring API.
Now to answer your question yes it is possible to fetch the name of bean via org.springframework.beans.factory.BeanNameAware.
The class for which you require the bean name should implement it and spring will auto-magically inject the name of the bean. However there is a gotcha which you should be aware and is mentioned in docs here

Related

UnderStanding of #Controller #Service #Repository

I have a doubt regarding dependency injection,Suppose my controller ,service,dao all are singleton so usually when we create the controller we inject the service as a instance variable of that class, but according to the singleton pattern if our controller is stateless then only we would not face any concurrency issue but here We are declaring the service dependency so it should not be stateless so we have to take care of synchronization?
Please clear this doubt as I am beginner so I hope its natural to have this doubt in mind,I don't know if I am thinking totally wrong.Please help.
All beans in Spring are Singleton by default. This includes any #Controller, #Service, #Repository and others, as well as any xml defined bean.
You could read this and this
From Java basic variable tutorial:
Local Variables Similar to how an object stores its state in fields, a
method will often store its temporary state in local variables. The
syntax for declaring a local variable is similar to declaring a field
(for example, int count = 0;). There is no special keyword designating
a variable as local; that determination comes entirely from the
location in which the variable is declared — which is between the
opening and closing braces of a method. As such, local variables are
only visible to the methods in which they are declared; they are not
accessible from the rest of the class.
If your service and controller are stateless, it's ok to inject one to another.
You should not declare any variable which keeps a state in these classes. final variables are ok.
If all operations are defined in methods and they don't use any variables of the classes, dependency injection that you're doing is totally safe.
That's why you need to use #Autowired when you declare a dependent service. Effectively handing the initialization process to the Spring framework instead of instantiating it yourself. Since Spring only has stateless beans, you're injecting one stateless singleton to another stateless singleton, so there's no need to manage thread manually.

Practical use of ApplicationContextAware in spring

I have had chance of working on only one project using spring , and the way it worked was
Make a singleton class (lets say MySpringHelper), that has method like getBean(String beanName)
What getBean(String) does is, it first checks existence of applicationContext, if it exists uses same to get the bean , else creates new applicationContext and returns the bean
Wherever in you project you need a bean simply call MySpringHelper.getBean("abc")
Keeping this in mind , when i was studying spring , i noticed interface "ApplicationContextAware" ... I am not sure when will this be needed, uses above pattern such interface seems not of any use. Or the above Singleton MySpringHelper pattern/approach is incorrect ??
Looking forward to learn from your experience
To give more details on application , its like a pdf file generator, 1 pdf file having 12-15 different charts, so the main method runs 1 thread for each chart , and inside these chart logic we are using singleton MySpringHelper
Why are you checking the existance of applicationContext? It should be there if your helper bean is configured in xml and has setter method in it. There is no need to create application context in that case.
For your case, I would suggest you get applicationContext injected by Spring rather than by using ApplicationContextAware.

Object created in Spring

I would like to know, whether this is a valid practice to use "new" in spring to create a Object?
You can either use xml->bean to create a object using xml file or use annotations to create a object.
This question arises when I am working on a project and where I want to create a object of a property class(which contains properties and setter/getter method of those properties).
I am able to create a object using new and its working fine but if spring has capability to create and manage object lifecycle then which way I need to go create a object and why?
I think the confusion may arise because of the (over)usage of spring as DI mechanism. Spring is a framework providing many services. Bean or dependency injection is just on of those.
I would say that for POJOs which have just setter and getters without much logic in them you can safely create objects using new keyword. For example, in case of value objects and data classes which do not have much configuration or life cycle events to worry about, go ahead and crate those using new keyword. If you repetitively create these objects and have fields which are not changing often, then I would use spring because it will lessen some of the repetitive code and object creation can be considered externalized or separated from your object usage.
Classes instantiated using spring bean definition xml/annotations are basically 'Spring-Managed' beans which mostly means that their life cycle, scope, etc are managed by spring. Spring manages objects which are beans, which may have some life cycle methods and APIs. These beans are dependencies for the classes in which the are set. The parent objects call some API of these dependencies to fulfil some business cases.
Hope this helps.
The Dependency Injection concept in spring is more useful when we need to construct an object that depends upon many objects, because it saves you time and effort for constructing as well as instantiating dependent objects.
In your case , Since it's a POJO class with only setters and getters , I think it is absolutely safe to instantiate it using a new keyword.

Regarding Instance in Spring mvc web application development

I am new to spring mvc web development. I have one query.
Suppose we are having different service classes. So do we have one instance of those classes per request OR only single instance of that class gets create. Actually i want to use instance variables , so with each request new instance will get created or it will be like singleton type of behavior. Hopefully i am able to explain my question.
you can have either, the default is a singleton - one instance. But this can be changed using bean scope.
obligatory link to offical docs correct chapter
(personally never needed to use anything other singleton)
If you have not defined any scope explicitly, it will be singleton by default, singleton means there will be one object per spring container, for your context, one object for all your request threads. In case of singleton scope, be cautious while using member variables, because thread safety comes into picture.
If you are modifying state of a member variable inside your singleton scoped bean, you need to write thread safe code because multiple threads are accessing your member variable and a race condition may occur.
Moreover, you can define other scopes too using #Scope at the class level(i.e above #Component) or at method level above #Bean annotations.
Generally, we keep using the default scope (i.e singleton scope), this way spring container also does not waste time in creating the new object of the bean asked for, though it would be a little overhead creating an object on each request thread.
If you want a new object on every bean injection, you can have prototype scope for that bean.

How to handle externally stored default values in Domain Class

I want to be able to set default values for some fields in my domain classes.
Till now I had a class which stored a Map of settings for my whole project, with a task in mind to move this map into a redis database.
The day has come and I moved all the data to redis and created a nice spring bean to get/set the values.
However...
it seems that default values are set on the domain class instance before bean is injected.
This kind of breaks the whole process.
Also... there's an issue with unit tests.
I've created a class which implements the same interface as the spring bean and holds test values. I wanted to inject it into domain classes, but this fails as well.
So right now I'm trying to find a good way to handle externally stored defauls values for my domain classes with ability to run unit tests.
Any thoughts?
There are a few different approaches you could take:
Introduce a separate bean with the default values so that those are supplied in the same way as they were before. In a separate higher level context or later on in application startup, you could then override the bean definition with the one that pulls from the database
Use a BeanPostProcessor or BeanFactoryPostProcessor to specify the default values, then use your new bean for retrieving new values
If neither of these answers is helpful, please post your setup and example code so I can get a clearer picture of what you're trying to do.
What I did in the end:
I've created a class which is connecting to Redis and gets me all the data I require.
For unit testing I've created a copy of this class, it implements the same interface but instead of getting the data from Redis it has a simple Map inside and get's the data from there. In the end it acts the same, but the data is stored internally. So in my unit tests I just inject this Unit test version of this class where appropriate.
Probably not the best solution there is but it worked for me for the last few months.

Resources