Spring can't created bean when class has $1.class - spring

When I compiled my java's file,and java compiler generated extra class,like example.class,example$1.class,example$2.class in my package,
and My ApplicationContext's file to scan component like this.
<context:component-scan base-package="com.test">
<context:include-filter type="regex" expression="com\.test\..*"/>
then I got this error message.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'example.1' defined in file [/tmp/jetty-0.0.0.0-8050-relayserver.war-_relayserver-any-2814616804903816631.dir/webapp/WEB-INF/classes/com/test/example$1.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.test.example$1]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.test.example$1.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1040)
For now,I just only set exclude filter to do this.

MyClass$1 (and $2 and so on) classes are generated for anonymous inner classes in your class. Anonymous inner classes are commonly used when using the listener pattern, they are defined like this:
MyInterface listener = new MyInterface() { // this is the anonymous inner class
... // implementation
}
So I guess you did try to use autowire on an anonymous inner class, which I suspect is not supported by spring (hard to say more without code).

Related

Spring singleton created, destroyed, created again

I am seeing a peculiar behavior in Spring 3.2.5
One of my beans is created as a consequence of AbstractBeanFactory#getType
Then Spring throws an exception along the lines of
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'A' defined in class path resource [config.xml]: Cannot resolve reference to bean 'B' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'B': Requested bean is currently in creation: Is there an unresolvable circular reference?
As the result of that exception, my bean is destroyed.
Later, my bean is created again, from a different getType() call. Tghis time Spring does not have any circular path problems.
Eventually, the entire context is created successfully, with the second copy of my bean retained as singleton.
My question is - is that behavior normal? Or am I doing something wrong? My bean has side effects in its init() method, so if this is a normal behavior of Spring, I'll need to add a destroy() method to it...
Edit:
To clarify the questions about the exception: The beans mentioned in exception are not exactly relevant because the context (including the beans A and B) is eventually created successfully, so there really is no circular dependency. However, for the completeness' sake, bean A takes bean B as constructor argument.

Bean's property is not setting from util:list object

I have declared following list using spring util namespace in my spring configuration file:
<util:list id="childList">
<ref bean="child1"/>
<ref bean="child2"/>
<ref bean="child3"/>
</util:list>
where all reference bean are marked with #Componant annotation and their respective beans are creating. But whenever I am trying to Autowired any beans property like:
#Component
public class ListTest{
#Autowired
#Qualifier("childList")
private List<IParent> list;
public List<IParent> getList() {
return list;
}
}
Gives exception as: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'listTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List com.spring3.componentScanFilterTest.ListTest.list; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring3.componentScanFilterTest.IParent] found for dependency [collection of com.spring3.componentScanFilterTest.IParent]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=childList)}
But instead of #Autowired and #Qualifier if I use as:
#Resource(name="childList")
It works. Why? As per my understanding #Autowired is used to autowire the property matching by type and #Qualifier is used to select any one bean from multiple ambiguous beans.
Please explain.
Spring docs says.
As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot injected through #Autowired, because type matching is not properly applicable to them. Use #Resource for such beans, referring to the specific collection or map bean by unique name.
Hope this clear your doubt.
Type matching is not properly applicable to beans which defined as collection.
If you intend to express annotation-driven injection by name, do not primarily use #Autowired - even if is technically capable of referring to a bean name through #Qualifier values. Instead, prefer the JSR-250 #Resource annotation which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans which are themselves defined as a collection or map type cannot be injected via #Autowired since type matching is not properly applicable to them. Use #Resource for such beans, referring to the specific collection/map bean by unique name.
Here:
http://docs.spring.io/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation-qualifiers
You are trying to get list of all beans of type Parent that have the qualifier "childList".

Spring - Instanciate a bean with a class which throws an Exception

I'm trying to instanciate a bean which constructor could throw an Exception.
I can't modify this class (given by an external team).
<bean id="myClass" class="myClass" />
The myClass constructor throws Exception.
I've been thinking about extending this class with a Singleton Pattern which is the behavior I want (be sure to instantiate only one instance of MyClass).
Error message :
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'myClass'
defined in class path resource
[.../spring_applicationContext.xml]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class
[myClass]:
Constructor threw exception; nested exception is
java.lang.ExceptionInInitializerError
Thanks in advance for your answers
I think the problem comes from the fact that my constructor throws an Exception.
My question is : with Spring, is it possible to instanciate a bean with a constructor which could throw an exception ?
If no bean scope is specified in bean configuration file, default to singleton. Your bean myClass is a singleton and you dont need to do anything more.
Spring Doc
Spring beans are by default singletons.
You should provide more of the stacktrace - what you're showing indicates that it is not myClass that is the problem, but the ClassPathXmlApplicationContext constructor that throws an exception - the cause usually follows later in the stacktrace.
Cheers,
As per stack trace, looks like there is an unexpected error either in static block or variable while creating an object of class 'myClass'.

Bean creation is failing (spring)

I am trying to create a bean and than trying to inject the same in my Controller but i am getting bean creation failure error.Here is my code
#Service("springSecurityLoginServiceImpl")
public class SpringSecurityLoginServiceImpl implements SpringSecurityLoginService
{
//impl
}
this is how i am trying to inject it in my controller
#Controller
#RequestMapping("springSecurity/login.json")
public class SpringSecurityLoginController
{
#Autowired
#Qualifier("springSecurityLoginServiceImpl")
SpringSecurityLoginService springSecurityLoginService;
}
There is no entry in Spring-MVC-config xml file except these annotation, but when i am starting server facing the following exception
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0'
defined in ServletContext resource [/WEB-INF/config/spring-mvc-config.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'springSecurityLoginController':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: com.core.servicelayer.user.SpringSecurityLoginService com.storefront.controllers.pages.SpringSecurityLoginController.springSecurityLoginService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.core.servicelayer.user.SpringSecurityLoginService] 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),
#org.springframework.beans.factory.annotation.Qualifier(value=springSecurityLoginServiceImpl)}
i am not sure what i am doing wrong or what extra i have to do
SpringSecurityLoginController class refers SpringSecurityLoginService class, for which a bean isn't defined. That much the error says.
It is true, because you've only defined a bean for the class LoginServiceImpl, which doesn't seem to extend SpringSecurityLoginService in any way.
Spring's bean lookup algorithm first searches for beans of which type is, or extends, SpringSecurityLoginService. Then, it narrows the avaialble options using the Qualifier. In this case, no bean is found in the first place...
See Spring doc:
4.11.3 Fine-tuning annotation-based autowiring with qualifiers
Since autowiring by type may lead to multiple candidates, it is often
necessary to have more control over the selection process. One way to
accomplish this is with Spring's #Qualifier annotation. This allows
for associating qualifier values with specific arguments, narrowing
the set of type matches so that a specific bean is chosen for each
argument.
You need that LoginServiceImpl will implement SpringSecurityLoginService, for instance.
EDIT
Since it was just a typo you might be not including SpringSecurityLoginService's package in component-scan tag, in your spring configuration file (as gkamal has already mentioned). You should have there something like:
<context:component-scan base-package="org.example"/>
where org.example should be replaced by SpringSecurityLoginService's package.

Error while injecting a Spring bean into a JSF ManagedBean

I have a JSF ManagedBean which has a property that should be set by Spring. However, I get the following error:
Caused by: javax.el.ELException: java.lang.IllegalArgumentException: Cannot convert persistence.AuthDao#2f6e6ad9 of type class $Proxy166 to class persistence.AuthDao
at com.sun.el.ExpressionFactoryImpl.coerceToType(ExpressionFactoryImpl.java:68)
at com.sun.faces.el.ELUtils.coerce(ELUtils.java:536)
at com.sun.faces.mgbean.BeanBuilder$Expression.evaluate(BeanBuilder.java:592)
at com.sun.faces.mgbean.ManagedBeanBuilder$BakedBeanProperty.set(ManagedBeanBuilder.java:606)
... 57 more
Caused by: java.lang.IllegalArgumentException: Cannot convert persistence.AuthDao#2f6e6ad9 of type class $Proxy166 to class persistence.AuthDao
at com.sun.el.lang.ELSupport.coerceToType(ELSupport.java:397)
at com.sun.el.ExpressionFactoryImpl.coerceToType(ExpressionFactoryImpl.java:66)
I have the ELresolver in faces-config.xml.
<managed-bean>
<managed-bean-name>authController</managed-bean-name>
<managed-bean-class>controllers.AuthController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>authDao</property-name>
<value>#{authDao}</value>
</managed-property>
</managed-bean>
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
It seems that it can find the class, but the class is of another type ($Proxy166?, not sure where that comes from).
PS: Removing the ELResolver seems to do the trick; I thought explicitly providing managed-bean in faces-config.xml would override ELResolver. Is there any way of both of these to coexist, then? Similarly, if I provide both annotation and XML configuration for a bean, which one of these is preferred, or is there a way to merge them, provide some properties in annotation, some in XML?
PPS: After adding interfaces and changing my current classes to implement them, I get the following error:
Error occurred during deployment: Exception while loading the app :
java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'authDao' defined in ServletContext resource
[/WEB-INF/applicationContext.xml]: Initialization of bean failed;
nested exception is
org.springframework.beans.ConversionNotSupportedException: Failed to
convert property value of type '$Proxy157 implementing
persistence.UserDao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised'
to required type 'persistence.UserDaoImpl' for property 'userDao';
nested exception is java.lang.IllegalStateException: Cannot convert
value of type [$Proxy157 implementing
persistence.UserDao,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised]
to required type [persistence.UserDaoImpl] for property 'userDao': no
matching editors or conversion strategy found. Please see server.log
for more details.
This is a proxy of your class. You are implementing an interface, so spring creates a proxy around the interface, but you are trying to inject by concrete type. Switch to the interface instead (in the managed bean).
If you really need for some reason to inject by concrete class, you can use #Scoped(proxyMode=ScopeProxyMode.TARGET_CLASS)

Resources