Spring dynamic wiring - spring

In the case of wiring in Spring (using the qualifier annotation), why spring does not allow the qualifier to be a dynamic value ?
For example I want to inject a notifier implemetation object in a person object based on a value found in the person object.
what would be the best solution for such situation?
thanks

Related

Use of #Scope annotation with Spring Controller

I am working on a project which is based on Struts 1.x, converting it to Spring 4. I have visited many tutorial sites and read Spring 4 tutorials but no one used #Scope annotation with #Controller in tutorial application. My Question is :
1) Is it compulsory to use #Scope attribute?
2) What if we do not use?
3) Is it good practice to use #Scope with #Controller?
We have also reading a property file at server start up and storing it into Property class. I am reading some property in DAOImpl class(Annotated as #Repository). If I use #Scope attribute with both Controller and Repository then it return value otherwise it return NullPointerException. Why is this behavior?
1) Is it compulsory to use #Scope attribute?
No. If you want the default ("singleton") then you don't need to specify.
2) What if we do not use?
Then your application will only create one instance of the bean.
3) Is it good practice to use #Scope with #Controller?
No. It does not make sense for an application to have more than one instance of a controller class (or a repository). If you have a need to use both annotations together, then you are not modelling your classes very well.
Why is this behavior?
Because the context cannot create a scoped bean to inject if the target bean is not being constructed in that scope (e.g. trying to inject a request-scoped bean into a bean that's being created outside the context of a request).
To solve this you need to use scoped-proxies, by setting proxyMode.
In your specific case, however, the solution is that you don't actually need non-default scope.
#Scope- Isn't Compulsory to use with #Controller, unless and until u need one based on your requirements. #Scope defines the scope of the bean, by default its singleton.
And also, Property Class should be managed by Spring, otherwise it will give you an exception.

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.

Custom annotation like #Value

I need to create a means to add a custom annotation like
#Value("${my.property}")
However, in my case I need to get the value from a database rather then a properties file.
Basically I would like to create a bean on container startup that reads in property name value pairs from a database and can then inject these into fields belonging to other beans.
Approach #1:
One way is to create an Aspect, with a point-cut expression that matches any method having this annotation.
Your aspect will then:
Read the property value in the annotation
Look up the required value an inject it into the class.
AOP Kickstart
Here's a guide to getting started with AOP in Spring
http://www.tutorialspoint.com/spring/aop_with_spring.htm
Joinpoint matching
Here's a reference that describes how to create a join-point that matches on annotations: http://eclipse.org/aspectj/doc/next/adk15notebook/annotations-pointcuts-and-advice.html
Approach #2:
Another way is to use a BeanFactoryPostProcessor - this is essentially how a PropertyPlaceholderConfigurer works.
It will look at your bean definitions, and fetch the underlying class.
It will then check for the annotation in the class, using reflection.
It will update the bean definition to include injecting the property as per the value in the annotation.
. . actually I think approach #2 sounds more like what you want - all of the processing happens on "start-up". . . (In actual fact your modifying the bean recipes even before startup). . whereas if you used AOP, you'd be intercepting method invocations, which might be too late for you?
Namespace Handler
If you wanted you could even create your own Spring namespace handler to turn on your post processor in a terse way. Eg:
<myApp:injectFromDb />
as an alternative to:
<bean class="MyDatabaseLookupProcessorImpl etc, etc. />
Update: Approach #3
As of Spring 3.1 there's also the PropertySourcesPlaceholderConfigurer, that will provide most of the plumbing for you, so you can achieve this with less code.
Alternatively you should be able to configure kind of properties repository bean and then use it in SpEL directly in #Value annotation.
Let's say you'd have bean called propertiesRepository in your context that implements following interface:
interface PropertiesRepository {
String getProperty(String propertyName);
}
then on bean where you want to inject values you can use following expression
#Value("#{propertiesRepository.getProperty('my.property')}")
String myProperty;
You can use #Value annotation by injecting database configuration in application environment itself.
I know this is an old question but I didn't find an exact solution. So documenting it here.
I have already answered the same on different forum.
Please refer to this answer for exact solution to your problem.

Spring #Cachable bean reference in key

I want to use the #Cachable annotation on one of my methods, but I have the problem, that the result depends on an attribute of a spring bean that is not part of the method signature.
So I want something like this:
#Cachable(value="mycache", key="#id, #myspringbean.referenceId")
MyResult myMethod(int id);
I guess these are actually two problems: How to get use a composite key and how to use another spring bean in the expression.
The problem of how to use a composite key can probably be solved like in this SO question: #Cacheable key on multiple method arguments
However, I could not find anythig about how to reference to another spring bean in this expression. Is it possible and if yes, how?
You can have a lot a details on SpEL in the Spring documentation (http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/expressions.html). As you can see, you can use bean references using the #myBean syntax. You have to include a bean resolver in your context to do that.
It's not possible to use the current Spring bean name.
I think I would use the following pattern so that each bean object will have it's own "key-space" see also What can be the default key generator.
As for the problem above one can use:
#Cachable(value="mycache", key = "{#id, #root.targetClass.getDeclaredField('attribute').get(#root.target)}")
MyResult myMethod(int id);
just make sure your attribute is public

How to control spring #transactional Annotation precedence?

The situation is that I am using Aspectj with spring aop,I define a aspect(After advice) to do some data opration for a method.And I also use the spring #transactional for the same method.
Now the question comes,how can I control the order for them to aspectj?
(I know how to control the two aspect defined by myself ,but I have no idea if one of them is spring #transactional )
Thank you very much for your help.
You can define relative order of transactional aspect using order attribute of <tx:annotation-driven>, it works the same way as orders of other aspects.

Resources