Spring AOP - Error Generating proxies - spring

I'm using spring AOP's around advice to capture processing time of a transaction. I'm getting the following error during application startup
error creating bean "coreMessageResourceAccesor"
Could not generate CGLIB subclass of class
[class org.springframework.context.support.MessageSourceAccessor]:
Common causes of this problem include using a final class or a non-visible class;
nested exception is java.lang.IllegalArgumentException:
Superclass has no null constructors but no arguments were given
I identified what the problem is with the help of this thread. But I cannot change coreMessageResourceAccesor bean to use setter based injection because its using a spring class & that class doesn't have no arg constructor
Below is the configuration for the bean
<bean id="coreMessageSourceAccessor"
class="org.springframework.context.support.MessageSourceAccessor" >
<constructor-arg type="org.springframework.context.MessageSource"
ref="coreMessageSource" />
</bean>
I would really appreciate if someone could help. Thanks for your time.

You don't need really need to configure MessageSourceAccessor accessor as a bean, it's generally easier to instantiate it manually as required. So rather than inject the MessageSourceAccessor into your beans, inject the raw MessageSource, and then wrap it in a MessageSourceAccessor as required (i.e. using new MessageSourceAccessor(messageSource)).
You can then put the advice around the MessageSource rather than the MessageSourceAccessor, which will work better. Also, MessageSourceAccessor will not itself add any significant processing time, it's just a thin wrapper around MessageSource.

Related

How to know if the wiring for a bean is complete with autowiring?

I have a bean with autowired beans.
So something like:
class A
{
#Autowired
B b;
#Autowired
C c;
void function()
{
// here I would like to do something when I an sure the wiring has been done
// being sure that I won't wait forever
...
Something has to exist, but I can't find it.
Thanks for your help!
You can annotate your 'function' method with #PostConstruct and specify <context:annotation-config/> in your spring config XML. Then, function will only be invoked after autowiring, so you could check in function whether your beans have been injected successfully.
A classic way to achieve this is to implement InitializingBean:
Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory: for example, to perform custom initialization, or merely to check that all mandatory properties have been set.
An alternative to implementing InitializingBean is specifying a custom init-method, for example in an XML bean definition. For a list of all bean lifecycle methods, see the BeanFactory javadocs.
I also suggest reading other answers:
How to call a method after bean initialization is complete?
What is the difference between BeanPostProcessor and init/destroy method in Spring?
If you are using default scope for beans that is singleton, then autowiring will always be done at the application startup only. If wiring for any field fails, then spring container will throw an exception and the application will not start properly. So, if the control of code is in your method , it means wiring has already been done.

Make a bean unautowireable or that disposes of it self?

We need a spring bean that will either
Prevent the framework from #Autowired -ing it.
or
Once it does its work it destroys itself?
The bean roughly looks like this:
public final class Registrar implements ApplicationListener<SOFrameworkInitializedEvent>
So after it receives this 1 time event do the work and go away. We are using Spring 3.0.7.
Use the autowire-candidate property in the bean definition XML, e.g.:
<bean id="MyBean" class="com.acme.SimpleTestServiceImpl" autowire-candidate="false"/>

What is the difference between BeanPostProcessor and init/destroy method in Spring?

What is the difference between implementing the BeanPostProcessor interface and either using the init/destroy method attributes in the XML configuration file in Spring or implementing InitializingBean/DisposableBean interface?
This is pretty clearly explained in the Spring documentation about the Container Extension Points.
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 initializing a bean, you can
plug in one or more BeanPostProcessor implementations.
So in essence the method postProcessBeforeInitialization defined in the BeanPostProcessor gets called (as the name indicates) before the initialization of beans and likewise the postProcessAfterInitialization gets called after the initialization of the bean.
The difference to the #PostConstruct, InitializingBean and custom init method is that these are defined on the bean itself. Their ordering can be found in the Combining lifecycle mechanisms section of the spring documentation.
So basically the BeanPostProcessor can be used to do custom instantiation logic for several beans wheras the others are defined on a per bean basis.
Above answers clearly explains some of the very important aspect.
Apart from that it's also important to understand that both beanPostProcessor and init and destroy methods are part of the Spring bean life cycle.
BeanPostProcessor class has two methods.
1) postProcessBeforeInitialization - as name clearly says that it's used to make sure required actions are taken before initialization. e.g. you want to load certain property file/read data from the remote source/service.
2) postProcessAfterInitialization - any thing that you want to do after initialization before bean reference is given to application.
Sequence of the questioned methods in life cycle as follows :
1) BeanPostProcessor.postProcessBeforeInitialization()
2) init()
3) BeanPostProcessor.postProcessAfterInitialization()
4) destroy()
You may check this by writing simple example having sysout and check their sequence.
Init and Destroy callback methods are part of Spring bean life cycle phases. The init method is going to be executed after bean instantiation. Similarly, The destroy method is going to be executed before bean finalization.
We can implement this functionality using implementing interfaces InitializingBean and DisposableBean, or using annotations #postconstruct and #predestroy, or declare the <bean> with init-method and destroy-method attributes.
BeanPostProcessor interface is used for extending the functionality of framework if want to do any configuration Pre- and Post- bean initialization done by spring container.
For Example: By default, Spring will not aware of the #PostConstruct and #PreDestroy annotation. To enable it, we have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean configuration file. Here CommonAnnotationBeanPostProcessor is predefined BeanPostProcessor implementation for the annotations. Like:
#Required enables RequiredAnnotationBeanPostProcessor processing tool
#Autowired enables AutowiredAnnotationBeanPostProcessor processing tool
And one more main diff is InitializingBean,DisposableBean related afterPropertiesSet() & destory() methods did not accept any paratmeters and return type also void, so we did not implement any custom logic.
But coming to BeanPostProcess methods postProcessBeforeInitialization(Object bean,String beanName) and postProcessAfterInitilization(Object bean,String beanName) are accept those two paramaters and return type also Object so we are able to write initilzation logics as well as any custom login based on the passing bean...
These both callback method feautes are including the bean life cycle and the following are the life cycle as follows
1) BeanPostProcessor.postProcessBeforeInitilazation()
2) #postConstruct or InitializingBean.afterPropertiesSet() or initialization method which is
defining in xml /* here also it's following the same oredr if three ways are availiable **/
3) BeanPostProcessor.postProcessAfterInitialization()
4) #preDestroy or DisposibleBean.destroy() or destroy method which is defining in xml
/* here also it's following the same oredr if three ways are availiable **/
Just a short supplement to all the answers above: If you have any generic logic, common logic that needs to be universally applied to all your Spring beans, such as the injection of a logger to your beans, setting of a properties file, setting default values to fields of your beans through reflection; you could put that logic into ONE single place: the #Overriden callbacks (eg: postProcessBeforeInitialization(Object arg0, String arg1) if you are implementing the BeanPostProcessor interface); instead of duplicating the same logic across all your beans.
a)The postProcessBeforeInitialization() will be called before initialization of the bean.
b)Once the bean gets initialized, the different callbacks methods are called in the following order as per the Spring docs:
Methods annotated with #PostConstruct
afterPropertiesSet() as defined by the InitializingBean callback interface
init method defined through the XML.
The main difference is that the above 3 methods get called after the initialization get completed by the postProcessBeforeInitialization() method.
Once these methods get completed the method postProcessAfterInitialization() will be called and then the destroy methods are called in the same order:
Methods annotated with #PreDestroy
destroy() as defined by the DisposableBean callback interface
destroy() method defined through the XML.

Why is there a need to specify the class in both the xml file and in the getBean() method in Spring

This might be an obvious but I'm having a hard time understanding why we need to define the class of a bean in two places....
From the spring reference manual...
...
<bean id="petStore"
class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
// retrieve configured instance
PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);
Shouldn't the xml fine be enough for the container to know the class of petStore?
You can use the following method:
context.getBean("petStore")
However, as this returns a java.lang.Object, you'd still need to have a cast:
PetStoreServiceImpl petstore = (PetStoreServiceImpl)context.getBean("petStore");
However, this could lead to problems if your "petStore" bean is not actually a PetStoreServiceImpl, and to avoid casts (which since the advent of Generics are being seen as a bit dirty), you can use the above method to infer the type (and let's spring check whether the bean you're expecting is really of the right class, so hence you've got:
PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);
Hope that helps.
EDIT:
Personally, I would avoid calling context.getBean() to lookup methods as it goes against the idea of dependency injection. Really, the component that uses the petstore bean should have a property, which can then be injected with the correct component.
private PetStoreService petStoreService;
// setter omitted for brevity
public void someotherMethod() {
// no need for calling getBean()
petStoreService.somePetstoreMethod();
}
Then you can hook up the beans in the application context:
You could also do away with the configuration via XML and use annotation to wire up your beans:
#Autowired
private PetStoreService petStoreService;
As long as you've got
in your spring context, the "petStore" bean defined in your application context will automatically be injected. If you've got more than one bean with the type "PetStoreService", then you'd need to add a qualifier:
#Autowired
#Qualifier("petStore")
private PetStoreService petStoreService;
There's no requirement to specify the class in the getBean() method. It's just a question of safety. Note there's also a getBean() that takes only a class so that you can just look up beans by type instead of needing to know the name.

when spring bean is loaded and if i have a constructor and setters which one will be called first?

This is a basic question - when spring bean is loaded and if i have a constructor and setters which one will be called first?
Thanks
The constructor must be called before any setter methods are called. Use the init-method to tell Spring to invoke some logic after the setters are called:
<bean class="my.CoolClass" init-method="startup">
<constructor-arg value="Foo" />
<property name="bar" value="baz" />
</bean>
Doesn't the constructor have to be called first? The setters are instance methods so that can't called until the object is instantiated.
I don't think Spring provides any guarantees about the order in which setters are called. It would be good practice to make your beans work regardless of which order the setters are called. If you want to do some processing after all the setters have been called, you might find that it's convenient to use a post construction method. Or if you are using XML configuration rather than annotations, an initialization method might suit.
I wrote simple XML config and step through Spring source code in debugger.
Seems that with Spring 3.x it's possible to combine constructor-arg and property in XML bean definition (check doCreateBean in AbstractAutowireCapableBeanFactory.java, which call createBeanInstance - constructor and populateBean next - setters).
See also https://softwareengineering.stackexchange.com/questions/149378/both-constructor-and-setter-injection-together-in-spring/

Resources