Spring use Autowired annotations gets wrong - spring

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/"/>
<property name="filterChainDefinitionMap" ref="chainFilterBuff" />
</bean>
<bean id="chainFilterBuff" class="org.moofie.test.security.FilterChainBean">
<property name="filterChainDefinitions">
<value>/test/login=anon</value>
</property>
</bean>
above is my spring config
private String filterChainDefinitions;
public String getFilterChainDefinitions() {
return filterChainDefinitions;
}
public void setFilterChainDefinitions(String filterChainDefinitions) {
this.filterChainDefinitions = filterChainDefinitions;
}
and this is my java code,it works fine with getter and setter,but I want to replace getter and setter with #autowired annotaion like this:
#Autowired
private String filterChainDefinitions;
it gets errors:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 34 more
So whats wrong with my code?or I should use other annotations?

The setter and getter way is working because, in your config XML you are calling the setter directly using the <property name="filterChainDefinitions"></property>.
#Autowired works on the bean that are declared explicitly.
If you want to use the #Autowired to set the filterChainDefinitions, then you must declare the it first like below:
<bean id="filterChainDefinitions" class="java.lang.String">
<constructor-arg value="/test/login=anon"/>
</bean>

Related

org.springframework.beans.factory.BeanCreationException: Could not autowire field:

I have problems with:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.hdx.ssm.service.ItemsService com.hdx.ssm.controller.ItemsController.itemsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.hdx.ssm.service.ItemsService] 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)}
This is ItemsController:
#Controller
#RequestMapping("/items")
public class ItemsController {
#Autowired
private ItemsService itemsService;
and ItemsService:
public interface ItemsService {
Implementation class:
public class ItemsServiceImpl implements ItemsService {
#Autowired
private ItemsMapperCustom itemsMapperCustom;
#Autowired
private ItemsMapper itemsMapper;
And some setting spring-mvc.xml:
<context:component-scan base-package="com.hdx.ssm.controller"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
How can i solve this problem?
You need to add #Service as shown below to your ItemsServiceImpl in order to Spring container to know that it is a Spring managed bean:
#Service
public class ItemsServiceImpl implements ItemsService {
#Autowired
private ItemsMapperCustom itemsMapperCustom;
#Autowired
private ItemsMapper itemsMapper;
//other code
}

Spring 3 Annotations with hibernate CRUD operations : #Autowired not working as expected

I'm currently using Spring 3 annotations along with hibernate 3 for the database connectivity. I also have to be using spring tiles.
My spring-servlet.xml is:
<context:annotation-config />
<context:component-scan base-package="com.xxx.controller,com.xxx.dao,com.xxx.service" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"
id="viewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/plugin/impl/tiles/springtiles-defs.xml</value>
</list>
</property>
</bean>
//Is this required????
<!-- <bean id="MyDAO" class="com.xxxx.MyDAOImpl"></bean>
<bean id="MyService" class="com.xxxx.MyServiceImpl"></bean> -->
My controller class :
#Controller
public class myController {
#Autowired
private MyService myService;
public myController() {
}
#RequestMapping(value="/index.do", method = RequestMethod.GET)
protected ModelAndView Submit(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stubs
System.out.println(" Inside the controller ");
</beans>
And my serviceImpl class:
#Service("MyService")
public class MyServiceImpl implements MyService{
#Autowired
MyDAO myDAO;
And my DaoImpl class :
#Repository/*("myDAO")*/
public class MyDAOImpl implements MyDAO{
List<String> clientList;
#Autowired
private SessionFactory sessionFactory;
private Session session;
private Session currentSession() {
return this.sessionFactory.getCurrentSession();
}
#Override
public List<ClientInfoBean> getClientList(String currentQrt) throws DataStoreException {
// TODO Auto-generated method stub
return (List<ClientInfoBean>) this.currentSession().
createCriteria("Select * from myTable);
}
It still gives the below exceptions.
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: private com.xxx.service.MyService com.xxx.controller.MyController.MyService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.service.MyService com.xxx.controller.MyController.MyService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 97 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 99 more
So the problem is your packages:
You have definition of services and daos in: com.xxx.service and com.xxx.dao
and your implementation in: com.xxx.serviceImpl and com.xxx.daoImpl.
Add in also <context:component-scan base-package="com.xxx.serviceImpl,com.xxx.daoImpl"/>
Next problem you are facing is transactional management:
You havent defined it in spring configuration. This is an example how to do this:
<!-- Hibernate 3 Annotation SessionFactory Bean definition-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.jdbc.batch_size">${batchSize}</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
And after this you need to mark a method or your service implementation as #Transactional to make spring care of this.
The exception is clearly telling you that the bean is not configured
NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService]
Can you check the case of the bean names that you given in annotations are matching with the parameter name. myService vs MyService.
Also adding a setter might be a good idea as spring can call setter to inject the dependency instead of using Reflection to inject it.
When you define
#Service("MyService")
public class MyServiceImpl implements MyService{
}
or
#Repository("MyDAO")
public class MyDAOImpl implements MyDAO{
}
you are actually telling spring to create bean with the name "MyService" & "MyDAO"
when you define like
#Autowired
private MyService myService;
#Autowired
private MyDAO myDAO;
you are asking from spring to give bean(s) with the name "myService" & "myDAO".
Since spring creates bean with the name which is different from what are you asking, it is giving the error.
You have to keep name of the bean in the #Service & #Repository annotation same as the variable name for the Interface.
#Service("myService")
public class MyServiceImpl implements MyService{
}
private MyService myService;
As you qualified your service as "MyService" , you can add qualifier as below to find it. By default spring should autowire by type , so component scan should load your service. If you are defining beans partially in xml and expecting other services to be autowired, you have to add in your spring-servlet.xml
#Autowired
#Qualifier("MyService")
private MyService myService;
Also change your controller class as MyController instead of myController.
And remove the constructor myController(), spring will construct for you controller bean. Try to remove all your constructors in all your spring bean classes, spring will construct for you. For the beginning you can avoid qualifying the beans, remove the names in brackets( "MyService", "MyDao" etc....)
Use
#Service
public class MyServiceImpl implements MyService
Instead of
#Service("MyService")
public class MyServiceImpl implements MyService{

UnsatisfiedDependencyException during Spring Injection

I am getting this error for using Spring injection using constructor argument:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'testIdCreator': Unsatisfied dependency
expressed through constructor argument with index 0 of type
[IdCreatorDao]: : No matching bean of type [com.dao.IdCreatorDao
Bean definition:
<bean id="testIdCreator" class="com.utils.TestIdCreator">
<constructor-arg ref="mydDao"/>
</bean>
<bean id="mydDao" class="com.dao.idCreatorDAOImpl">
<constructor-arg ref="somedatasource" />
<constructor-arg value="${somedatasource.schema}" />
</bean>
Bean usage:
public class TestIdCreator{
private final IdCreatorDao idDao;
#Inject
public TestIdCreator(IdCreatorDao idDao) {
this.idDao= idDao;
}
}

Spring WebserviceTemplate not being registered

I am getting an error which i am not able to figure out what it is for related to Spring WebserviceTemplate.
here is the Class definition: (Interesting part is if i Remove the #Service annotation, it works fine.)
#Service
public class PTSWebServicesClientStubImpl implements PTSWebServicesStub
{
#Autowired
#Qualifier("PTS")
private WebServiceTemplate ptsWebServiceTemplate;
.....//
}
here is the xml configuration:
<bean id="ptsWebServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<qualifier value="PTS" />
<constructor-arg ref="messageFactory" />
<property name="marshaller" ref="ptsJaxbMarshaller" />
<property name="unmarshaller" ref="ptsJaxbMarshaller" />
<property name="interceptors">
<list>
<ref bean="loggingInterceptor" />
</list>
</property>
</bean>
When i try to deploy this or call it from Junit test, i get the below error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.ws.client.core.WebServiceTemplate] 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=PTS)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 100 more
You don't need the Qualifier annotation if you use the same name for the attribute and for the Spring bean id.
If you still want to, use "ptsWebServiceTemplate" for the attribute value of the Qualifier annotation.
The qualifier element in the XML is intended for custom Qualifier annotation types (your own annotation annotated with #Qualifier itself)

Manually wiring bean (has autowired dependency): Failed to convert

In a util class I want to use one of my services.
Now this service is wired, but the util isn't.
So in my Util class I do:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"});
UserService userService = (UserService) ((BeanFactory)context).getBean("userServiceWired");
In my context.xml I do:
<bean id="userServiceWired" class="com.daniels.jack.service.userServiceImpl">
<property name="restTemplate" value="restTemplateWired" />
</bean>
<bean id="restTemplateWired" class="org.springframework.web.client.RestTemplate"/>
But I get:
Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.client.RestTemplate'
On the UserService userService = ... line.
Use ref instead of value
<property name="restTemplate" ref="restTemplateWired" />

Resources