spring #autowired - java

to use #autowired. in xml, i only need to included
<context:annotation-config /> ?
is there any other tag i need to put ? need to put componenet-scan ?
weird, i get error below
ERROR - ContextLoader.initWebApplicationContext(203) | Context initialization fa
iled
org.springframework.beans.factory.BeanCreationException: Error creating bean wit
h name 'org.springframework.context.annotation.internalRequiredAnnotationProcess
or': Initialization of bean failed; nested exception is org.springframework.bean
s.InvalidPropertyException: Invalid property 'order' of bean class [org.springfr
amework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor]: No proper
ty 'order' found
Caused by:
org.springframework.beans.InvalidPropertyException: Invalid property 'order' of
bean class [org.springframework.beans.factory.annotation.RequiredAnnotationBeanP
ostProcessor]: No property 'order' found
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrap
perImpl.java:376)
at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1105)
at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBean

The <context:annotation-config /> option was introduced in Spring 2.5. Under the covers, this creates and configures a RequiredAnnotationBeanPostProcessor, and uses the order property of that. In Spring 2.0, RequiredAnnotationBeanPostProcessor exists, but has no order property.
My guess is that you have both Spring 2.5 and 2.0 on your classpath. The copy of 2.5 would have allowed you to use <context:annotation-config />, but then it used the 2.0 copy for RequiredAnnotationBeanPostProcessor.

This looks like a class path issue. Do you mix incompatible versions of different Spring jars, or are there multiple RequiredAnnotationBeanPostProcessor classes on your classpath?
Earlier versions of that class (up to 2.0.x) did not have an order property.

Related

Autowired class from the jar file outside the classes

How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.
SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
code:
package com.path.controller;
import org.quartz.Scheduler;
#Controller
public class MyController{
#Autowired
Scheduler scheduler;
}
This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,
<context:component-scan base-package="com.path" />
When you export the jar file using the export utility in eclipse there is a option called Add directory entries. Check this option and export the jar file, this will solve the problem
I'm guessing you haven't defined your scheduler bean. You need to first define the bean in order to inject into your controller.
In your applicationcontext.xml first define a bean with type Scheduler.
You might need something like below. Be sure to check out the quartz documentation to check which scheduler you need and how to instantiate it.
<bean id="schedulerFactory"
class="org.quartz.StdSchedulerFactory" />
<bean id="scheduler" class="org.quartz.Scheduler" factory-bean="schedulerFactory" factory-method="getDefaultScheduler" />
As the exception complains "No qualifying bean of type [org.quartz.Scheduler]" , we will have to define the bean of type org.quartz.Scheduler, But that is not possible without any concrete implementation of the same, So , we will have to get a concrete implementation from the Factory class org.quartz.impl.StdSchedulerFactory and it's non static method getScheduler().
Hence, you will have to add following two lines in you context xml file and it will work , I have verified the same with the same version of spring which you are using :
<bean id="schedulerFactory" class="org.quartz.impl.StdSchedulerFactory" />
<bean id="scheduler" class="org.quartz.Scheduler" factory-bean="schedulerFactory" factory-method="getScheduler" />
A console output after printing the initialized bean gives this :
scheduler=org.quartz.impl.StdScheduler#536aaa8d

ConflictingBeanDefinitionException with non existing class

I have a wird problem with Spring. I'm working on a small mvc application and after some work I'm faceing such a problem:
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'userServiceImpl' for bean class [com.(...).servlet3.UserServiceImpl] conflicts with existing, non-compatible bean definition of same name and class [com.(...).service.UserServiceImpl]
This exception looks like sefl-explain but there is one thing wird: I do not have such class as [com.(...).servlet3.UserServiceImpl]. I used to have, but moved to another package. My structure looks like this:
Does anyone has faced such a problem?
You have to check get and set method in bean for path bean definition or path name seems duplicate.

java - #Aspect value attribute - Prototype scoped aspect bean

I am trying to create Aspect using Spring AOP and AspectJ.
#Aspect(value = "perthis(execution(* x.y.z.command.Command.execute()))")
public class CommandAdvice {
// Advices....
}
The Javadoc for the 'value attibute says:-
Per clause expression, defaults to singleton aspect.
Valid values are "" (singleton), "perthis(...)", etc
Everything works file without specifying the 'value' attribute in #Aspect annotation.
Using the above perthis setting resulted in following exception:-
Caused by: java.lang.IllegalArgumentException: Bean with name 'commandAspect' is a singleton, but aspect instantiation model is not singleton.
So I tried changing scope of advice bean to prototype:-
<bean id="commandAspect" class="x.y.z.command.CommandAdvice" **scope="prototype"**
factory-method="aspectOf" />
This resulted in :-
Caused by: java.lang.IllegalArgumentException: Can not set x.y.z.command.Command field x.y.z.test.CommandTest.command to sun.proxy.$Proxy30
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
at java.lang.reflect.Field.set(Field.java:657)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
My requirement is to create 'prototype' scoped Aspect bean.
Is prototype Aspect bean advisable? What are Pros and Cons in multi-threaded environment?
How to do it using that 'value' attribute?

No bean named but bean is defined

I'm working on an update version of grail-oauth-plugin that support last spring-oauth
My plugin version works good and I have implemented a workin oauth2 server.
But now I want to add a custom-grant defined like this
def doWithSpring = {
myTokenGranter(MyTokenGranter)
xmlns oauth:"http://www.springframework.org/schema/security/oauth2"
oauth.'authorization-server'( /* ... many definitions here ... */){
/* ... many definitions here ... */
oauth.'custom-grant'('token-granter-ref': "myTokenGranter")
}
}
But I get an exception telling me:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTokenGranter'
But the bean myTokenGranter is defined as you can see. And If I remove the custom-grant definition the project starts and I can access the myTokenGranter bean.
Looking to a fullstack trace I see that the exception occur in the spring oatuh2 server bean definition parse AuthorizationServerBeanDefinitionParser.java in the line where it try to find my bean
parserContext.getRegistry().getBeanDefinition(customGranterRef);
where customGranterRef = "myTokenGranter"
so I suspect there is a bug in Spring Ouath or in Grails BeanBuilder that does not let my "myTokenGranter" to be visible in the server parser. Or making some error in grails bean definition DSL.
Thank you for your interest.
Debugging the app more deeply I have found that the problem probably is in how grails BeanBuilder work in translating namespaced spring DSL.
If I debug the point where my bean is checked (in AuthorizationServerBeanDefinitionParser.java)
at row
parserContext.getRegistry().getBeanDefinition(customGranterRef);
if I check che result of
parserContext.getRegistry().getBeanDefinitionNames()
it show me only this beans
[org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0
org.springframework.transaction.interceptor.TransactionInterceptor#0
org.springframework.transaction.config.internalTransactionAdvisor
oauth2TokenGranter
oauth2AuthorizationCodeServices
oauth2AuthorizationRequestManager]
And not all other decleared beans...
The problem exist even if I move the ouath server declaration inside resources.xml, keeping my custom token granter bean declaration inside resources.groovy.
But the problem solves if I move the custom token bean declaration inside resources.xml.
I don't really know how the BeanBuilder DSL works, but it seems like the problem is there if there is a problem (your example works just fine in XML). Can you do it in two steps, so the bean definition for myTokenGranter is definitely available when the OAuth2 namepsace is handled?
Solved hacking Spring Security Oauth
see this commit

Autowiring priority

<beans default-autowire="byType" />
means that all fields of beans will automatically have dependencies injected if there is no more than 1 bean with the desired type.
I wonder if there is a way to define some sort of priority order (based on naming convention for example) for the auto-wiring in the case where there are more than one bean of the desired type.
Thanks in advance.
Edit: I just want to add that i'm not allowed to use annotations such as #Component and #Qualifier in the project i'm currently working on.
No there is not, but you can override this behavior as needed for each bean e.g.specify something like this where required:
<beans default-autowire="byType" >
<bean id="..." autowire="byName">
....
</bean>
</beans>
From spring 2.5 upwards when using the <context:component-scan/> to autowire beans via #Autowired you can also add #Qualifier where needed to specify a bean by name if there are multiple beans of the same type.
As stated in the spring documentation there are a few different ways to specify autowiring:
no - do not autowire, this is the default
byType - property type must match bean type, if more than one bean of that type is exists then an exception is thrown
byName - bean name must match property name
constructor - basically the same as byType but for constructors, spring picks the constructor with the most matches
autodetect - same as byType unless there is no default constructor where it falls back to constructor autowiring

Categories