I'm working through Peter Mularien's Spring Security 3, and am having a problem setting up the UserDetailsManager.
I create the JdbcUserDetailsManager bean as follows:
<bean id="jdbcUserService" class="org.springframework.security.provisioning.JdbcUserDetailsManager">
<property name="dataSource" ref="mySqlDb" />
<property name="authenticationManager" ref="authenticationManager" />
</bean>
and autowire its UserDetailsManager interface in my controller like so:
#Autowired
public UserDetailsManager userDetailsManager;
When I start up the app to test it out, I get the following exception:
Error creating bean with name 'changePasswordController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.provisioning.UserDetailsManager com.ebisent.web.ChangePasswordController.userDetailsManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.security.provisioning.UserDetailsManager] is defined: expected single matching bean but found 2: [org.springframework.security.provisioning.JdbcUserDetailsManager#0, jdbcUserService]
I searched through my project to see if I might have set up (Jdbc)UserDetailsManager elsewhere, but I don't appear to have done so. If I remove the "id" attribute in the bean definition, then the ambiguity is between JdbcUserDetailsManager#0 and JdbcUserDetailsManager#1.
My web.xml references app-config.xml in two places:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/app-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
There was definitely a problem with specifying app-config.xml twice, but that's not the answer to the problem originally stated.
It appears that Spring autowires based on type. The bean is defined with the class JdbcUserDetailsManager, which implements UserDetailsManager.
In my controller, I am autowiring the interface UserDetailsManager. Spring finds the interface twice, and complains that it doesn't know which to pick.
Adding the #Qualifier annotation fixes the problem. Here's how it looks now:
#Autowired
#Qualifier("jdbcUserService") // <-- this references the bean id
public UserDetailsManager userDetailsManager;
Robert,
Yes. What your web.xml says is to create a web app context of app-config.xml pointing to a parent of app-config.xml. That means you have two copies of each bean - which as you've noticed is incorrect.
this seems to do the trick:
Comment the "jdbcUserService"
Insert:
<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
</authentication-manager>
Create a datasource:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/secureApp"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
Create the nessecary config depending on witch datasource you are using (MySQL in this case). Create any additional config if you are using hibernate or jpa ...
Run the server.
I was able to reproduce this today. The database got updated with the changed password. It seems that the authentication-manager already instantiates a JdbcUserDetailsManager ??
Related
I have created a spring-config.xml file.In that file I have created all beans for service class and DAO class.Now I want to call the bean in my Spring controller.The method I already know is
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
SeviceClassName objService = (SeviceClassName) context.getBean("BeanName");
But the problem is I have put the file in WEB-INF folder.
To metigate the problem I have used
ApplicationContext context = new FileSystemXmlApplicationContext("C:/Users/xyz/Desktop/HelloWeb/WebContent/WEB-INF/spring-config.xml");
It's working fine.
But it doesn't seem to be a good practise.
Then I have tried to initialize the DispatcherServlet by spring-config.xml.
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
But I don't konw how to call the bean in controller.
I tried to use #Autowired in my spring controller.But it is not working.
Whenever I try this (#Autowired) and try to excecute a jsp file of the same application in eclipse it shows 'requested resource not avaliable".
Can any one suggest me how to solve the problem.
Or
Can anyone suggest me a better approach by which I can invoke a bean of service class which I have created in spring-config.xml.
Or
any other approach for invoking service class methods in spring controller.
I am using spring 3.0.
I have created a Dynamic Web Project in Eclipse.In my WEB-INF folder I have put 4 xml file
--web.xml,spring-config.xml,HelloWeb-servlet.xml .
My HelloWeb-servlet contains
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.tutorialspoint" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
My spring-config contains all the bean configuration.In the spring controller I just to invoke the service method which are written in the service class for which I have already created bean in spring-config.xml.
Check this Stackoverflow answer. It is probably a much more detailed answer than what you are looking for, but it will definitely help you go through the basics.
Essentially, a root context established via a Spring context loader listener, and a servlet context established via the corresponding servlet parameter. The param name for both are contextConfigLocation(former is a listener context-param and the latter is a servlet init-param).
#Autowired or #Inject can be used to inject the service bean in the controller. Make sure that the service bean is annotated with #Service or #Resource so the bean is picked up during component scanning.
I am getting the following error when attempting to navigate to the /connect endpoint of the spring social web module.
What I am getting:
[Request processing failed; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'scopedTarget.connectionRepository'
defined in ServletContext resource [/WEB-INF/appContext.xml]:
Initialization of bean failed; nested exception is
org.springframework.aop.framework.AopConfigException:
Could not generate CGLIB subclass of class
[class org.springframework.social.connect.jdbc.JdbcConnectionRepository]:
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]
Relevant portions of web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/appContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Relevant portion of appContext.xml:
<bean id="connectionFactoryLocator"
class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
<property name="connectionFactories">
<list>
<bean class="org.springframework.social.facebook.connect.FacebookConnectionFactory">
<constructor-arg value="${facebook.clientId}" />
<constructor-arg value="${facebook.clientSecret}" />
</bean>
</list>
</property>
</bean>
<bean id="usersConnectionRepository"
class="org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository">
<constructor-arg ref="dataSource" />
<constructor-arg ref="connectionFactoryLocator" />
<constructor-arg ref="textEncryptor" />
</bean>
<bean id="connectionRepository" factory-method="createConnectionRepository"
factory-bean="usersConnectionRepository" scope="request">
<constructor-arg value="#{request.userPrincipal.name}" />
<aop:scoped-proxy proxy-target-class="false" />
</bean>
Thank you for any responses.
I find this link useful https://github.com/socialsignin/socialsignin-showcase/issues/6, It solved my problem.
Basically in this case problem is with AOP proxy, for some reason CGLIB proxying not working in this case. so you have to turn it off and switch to JDK proxy. So what i did was just make this change in my context.xml -
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true"/>
to
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="false"/>
By making proxy-target-class="false" spring will use JDK proxy (don't ask why i have no idea).
It's solved my problem.
But if it doesn't work for you, then also change this:
<security:global-method-security proxy-target-class="false" >
and this:
<bean id="connectionFactoryLocator" class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
<property name="connectionFactories">
<list>
<bean class="org.springframework.social.facebook.connect.FacebookConnectionFactory">
<constructor-arg value="xxxxxxxxxxx" />
<constructor-arg value="xxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</bean>
</list>
</property>
<aop:scoped-proxy proxy-target-class="false"/>
</bean>
Hope this helped. Happy coding :)
I had similar issue, however I didn't use any of xml configs, everything was autoconfigured by spring-boot.
Here is what I got trying to do a /connect/facebook:
There was an unexpected error (type=Internal Server Error,
status=500). Error creating bean with name
'scopedTarget.connectionRepository' defined in class path resource
[org/springframework/social/config/annotation/SocialConfiguration.class]:
Initialization of bean failed; nested exception is
org.springframework.aop.framework.AopConfigException: Could not
generate CGLIB subclass of class [class
org.springframework.social.connect.jdbc.JdbcConnectionRepository]:
Common causes of this problem include using a final class or a
non-visible class; nested exception is
org.springframework.cglib.core.CodeGenerationException:
java.lang.reflect.InvocationTargetException-->null
The root cause was having spring-boot-devtools in the classpath. Removing devtools solved the problem. I also found a PR opened by some guy, please leave a comment there to bring more attention to the issue.
pull request
Upd. the PR was merged and starting from 2.0.0.M1 there is no issue with dev-tools anymore.
there is two methods to slove this problem for springboot project:
removing spring-boot-debtools dependency.
setting spring.aop.proxy-target-class=false in your application.properties.
I know this post is very old, however, the exception
Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class ... brought me here.
The solution for me was a default constructor.
The solution for me was to remove final from class definition.
I got the same exception while using PreAuthorize annotation on some Rest Controllers.
The problem was that the controller classes where defined as final and it caused such error.
I am quite new to Spring and Java world. I am trying to write a web app looking at petclinic application provided in the samples. However, I am hitting this roadblock since yesterday. It will be great if someone can point me in right direction. I looked up many links on google, but none of the solutions worked for me.
Here is the error root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:949)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795)
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
.
.
.
Here is my web.xml in WEB-INF
<display-name>Game's List</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext-hibernate.xml</param-value>
</context-param>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<servlet>
<servlet-name>gamelist</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>gamelist</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Here is the applicationContext-hibernate.xml
<!-- ========================= RESOURCE DEFINITIONS ========================= -->
<!-- import the dataSource definition -->
<import resource="applicationContext-dataSource.xml"/>
<!-- Configurer that replaces ${...} placeholders with values from a properties file -->
<!-- (in this case, Hibernate-related settings for the sessionFactory definition below) -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<context:annotation-config />
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:mappingResources="gamelist-hibernate.xml">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
</props>
</property>
<property name="eventListeners">
<map>
<entry key="merge">
<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
</entry>
</map>
</property>
</bean>
<!-- central data access object: Hibernate implementation -->
<bean id="gameDataStore" class="com.gamelist.datastore.GameItemDataStore"/>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->
<!--
Activates various annotations to be detected in bean classes:
Spring's #Required and #Autowired, as well as JSR 250's #Resource.
-->
<context:annotation-config/>
<!--
Instruct Spring to perform declarative transaction management
automatically on annotated classes.
-->
<tx:annotation-driven/>
<!--
Exporter that exposes the Hibernate statistics service via JMX. Autodetects the
service MBean, using its bean name as JMX object name.
-->
<context:mbean-export/>
This is gamelist-servlet.xml
<context:component-scan base-package="com.gamelist"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
This is the controller class
public class GameLibraryController {
private IDataStore gameDataStore;
#Autowired
public GameLibraryController(GameItemDataStore gameDataStore){
this.gameDataStore = gameDataStore;
}
#RequestMapping("/addGame")
public String addNewGame(Model model){
model.addAttribute("gameItem",new GameItem());
return "library/addgameform";
}
#RequestMapping("/addGameSubmit")
public void add(#ModelAttribute GameItem gameItem,BindingResult result, SessionStatus status){
this.gameDataStore.add(gameItem);
status.setComplete();
}
}
This is the hibernate implementation class GameItemDataStore
#Repository
#Transactional
public class GameItemDataStore implements IDataStore{
private SessionFactory sessionFactory;
#Autowired
public GameItemDataStore(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void add(BaseItem newGame){
sessionFactory.getCurrentSession().save(newGame);
}
}
This is the IDataStore interface
public interface IDataStore {
public void add(BaseItem newGame);
}
To avoid any confusion, I am going to assume the configuration you mentioned in the question, and start from there. (Ignoring the changes you may have tried after reading the comments on your question)
First a little background:
There are two contexts at play in a Spring MVC application. The applicationContext which is more accurately referred to as the ROOT WebApplicationContext, which is meant to be available to all Servlet level spring contexts, through an integration with the Servlet Container's lifecycle implementation. The second type of context is loaded for each DispatcherServlet configured in the web.xml lets call it ServletApplicationContext
Now, when the container starts, the Root application context is loaded
When the Servlet is loaded, the Servlet Application Context is loaded. At this point, beans from the Root Application Context are available to the Servlet Application Context.
IF, you do end up loading the same bean definitions in both the contexts, its like overriding beans in the Servlet Context. Very inefficient to load duplicate beans, and can cause weird errors if you are relying on the same instance being available in all context. But, for simple cases like a single servlet deployment, this should not cause your application to break at startup, spring will deal with this.
Now getting to what's wrong with your configuration:
There is no ContextLoaderListener configured in your web.xml. Without a ContextLoaderListener, the ROOT application context is NOT loaded. So none of the beans from /WEB-INF/spring/applicationContext-hibernate.xml are loaded.
When your servlet kicks up, it loads the beans from gamelist-servlet.xml, and cannot locate a sessionFactory bean, because the ROOT Web Application Context was never loaded~!
To confirm this, for a test, comment out all bean definitions from the two context files, just keep empty <beans></beans> tags in them. Start your server, you'll see a log statement at the end that says something like no ROOT Web Application Context found, configure ContextLoaderListener in web.xml
And the fix:
Add the ContextLoaderListener to your web.xml
You may choose to continue your configuration as you have it now, or follow the advice given in earlier comments and include only MVC related definitions in the servlet context and all else in the ROOT application context.
Another, simpler option would be to simply have an empty application context xml for the ROOT Web Application Context, and configure all beans in the servlet context. This is not correct from a purist design point of view, but a practical simple solution, provided you plan on having a single servlet application.
Sorry for the looong description, but I felt some explanation was mandated. Hope this helps.
Get rid of
<bean id="gameDataStore" class="com.gamelist.datastore.GameItemDataStore"/>
which you won't need because of #Repository on your class and
<context:annotation-config />
which you have twice. Then add
<context:component-scan base-package="com.your.package" />
where com.your.package is a top level package that contains the GameItemDataStore class.
i've problems in order to autowire a service in my controller. I've this error:
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 es.unican.meteo.service.UserService es.unican.meteo.controller.MyController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [es.unican.meteo.service.UserService] 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)}
It seems that the userService is not registered, so that, the controller can't get the bean. I thought that my config was ok because it works with the tests. In the tests i have this:
ClassPathXmlApplicationContext("/WEB-INF/app-config.xml");
and i can get the bean ok from the ApplicationContext.xml
My package structure is the following:
es.unican.meteo.controller
|---- MyController.java
es.unican.meteo.service
|---- UserService.java
es.unican.meteo.service.impl
|---- UserServiceImpl.java
.....
WebContent/WEB-INF
|---- MyDispatcherServlet-servlet.xml
|---- app-config.xml
|---- web.xml
.....
The clases:
== UserServiceImpl.java ==
#Service
public class UserServiceImpl implements UserService{
#Autowired
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
== MyController.java ==
#Controller
public class MyController {
#Autowired
private UserService userService;
#RequestMapping(method=RequestMethod.GET, value="/home")
public String handleRequest(){
return "welcome";
}
#RequestMapping(method=RequestMethod.GET, value="/getUsers")
public #ResponseBody List<User> getUsersInJSON(){
return userService.getUsers();
}
}
== web.xml ==
<display-name>Spring MVC</display-name>
<servlet>
<servlet-name>MyDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyDispatcherServlet</servlet-name>
<url-pattern>*.go</url-pattern>
</servlet-mapping>
</web-app>
== app-config.xml ===
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="es.unican.meteo" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
p:url="jdbc:derby:C:\tools\derbydb"
p:connectionProperties=""
p:username="APP"
p:password="" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/mybatis-config.xml" />
</bean>
<bean id="usersMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="es.unican.meteo.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="rolesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="es.unican.meteo.dao.RoleMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
== MyDispatcherServlet.xml ==
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- Enabling Spring beans auto-discovery -->
<context:component-scan base-package="es.unican.meteo.controller" />
<!-- Enabling Spring MVC configuration through annotations -->
<mvc:annotation-driven />
<!-- Defining which view resolver to use -->
<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Spring mvc logger trace:
19:38:54,119 DEBUG http-8080-1 support.DefaultListableBeanFactory:430 - Creating instance of bean 'myController'
19:38:54,170 DEBUG http-8080-1 annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.controller.MyController]: AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.controller.MyController.userService
19:38:54,174 DEBUG http-8080-1 support.DefaultListableBeanFactory:504 - Eagerly caching bean 'myController' to allow for resolving potential circular references
19:38:54,206 DEBUG http-8080-1 annotation.InjectionMetadata:85 - Processing injected method of bean 'myController': AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.controller.MyController.userService
19:38:54,224 DEBUG http-8080-1 support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'userServiceImpl'
19:38:54,226 DEBUG http-8080-1 support.DefaultListableBeanFactory:430 - Creating instance of bean 'userServiceImpl'
19:38:54,234 DEBUG http-8080-1 annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.service.impl.UserServiceImpl]: AutowiredFieldElement for private es.unican.meteo.dao.UserMapper es.unican.meteo.service.impl.UserServiceImpl.userMapper
19:38:54,237 DEBUG http-8080-1 support.DefaultListableBeanFactory:504 - Eagerly caching bean 'userServiceImpl' to allow for resolving potential circular references
19:38:54,256 DEBUG http-8080-1 annotation.InjectionMetadata:85 - Processing injected method of bean 'userServiceImpl': AutowiredFieldElement for private es.unican.meteo.dao.UserMapper es.unican.meteo.service.impl.UserServiceImpl.userMapper
19:38:54,268 INFO http-8080-1 support.DefaultListableBeanFactory:433 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#56088b29: defining beans [myController,roleService,userServiceImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
19:38:54,279 ERROR http-8080-1 servlet.DispatcherServlet:457 - Context initialization failed
I've reviewed some questions about this topic but i don't find a solution to my problem. Maybe i'm skipping something but i don't know certainly. I tried to change the component-scan with no results.
When i try to access to /SPRING-MVC/getUsers.go appears those errors.
I don't know if the beans must be placed in app-config (applicationContext) or in the servlet.xml because it is a little bit confusing...
Thank you
Your configuration is very strange...
First rule out the obvious
I don't see root web application context configuration in your web.xml. Could it be that you forgot to add this piece of code?
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/app-config.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Now a little bit of theory
Bit of Spring theory - Spring uses application context hierarchy for web applications:
top level web application context is loaded by ContextLoaderListener
then there are separate contexts for each DispatcherServlet instances
When a new bean is being instantiated, it can get dependencies either from the context where it is being defined or from parent context. This makes possible to define common beans in the root context (services, DAO, ...) and have the request handling beans in servlet application contexts as each servlet can have its own set of controllers, view handers, ...
Last, but not least - your errors
You are configuring MVC in your root context. That is just wrong. Remove the <mvc: context from there.
You are also registering your controllers in the root context via the <context:component-scan> on your base package. Make the component scan just on the services package or separate your classes into two top level packages core (for the root beans) and servlet (for servlet beans).
Make sure that your UserServiceImpl is in same package as defined in context:component-scan. If it's not, spring will not be able to detect it. Also, try removing value attribute from UserServiceImpl definition, since there is only 1 bean of that type. Spring will be able to autowire it by type.
You need to change the way you have autowired the service in the controller.
Change the following code
#Autowired
private UserService userService;
with following
#Resource(name="userService")
private UserService userService;
Because in the UserServiceImpl you have defined the #Service annotation with alias "userService".
I hope this would resolve your problem. :)
when ever you face such kind of problem kindly check, what is the path for context:component-scan basepackage
it should be root name Like if I am taking com.mike as package name & which contain bean,controller,dao,service folder in its structure then, in such condition you have to follow Like ----context:component-scan basepackaage="com.mike.*"
where * means all the folder (bean,service,dao,controller and theie corresponding classes) will be scaned.
You can use the #Qualifier annotation as follows:
#Autowired
#Qualifier("userService")
private UserService userService;
On first glance the config seems ok, yet there may be some smaller tripwires that might be not that obvious.
a) implemented UserService interface, is it the same as the controller needs? Dumb question, I know, but just be on the safe side.
b) bean name: Try eradicating the value-value (ba-da-tush) from the #Service annotation, its superflous anyway. Or be more specific with the help of an #Qualifier.
c) package scanning: Double check if your implemented service is really within es.unican.meteo. Sometimes its the small things.
Add #Component annotation on your service. It should work fine
I'm trying to set up a Spring configuration with tutorials and some stuff. It seems everything is OK but when I call the constructor of a Bean with a #Resource everything blows up.
I'm am also giving a try to Apache Click killing two birds with one stone.
Please, can anyone tell me what happens here and how could I fix this?
Thank you.
The error:
Caused by: java.lang.RuntimeException: No Context available on ThreadLocal Context Stack
at org.apache.click.Context$ContextStack.peek(Context.java:934)
at org.apache.click.Context$ContextStack.access$000(Context.java:885)
at org.apache.click.Context.getThreadLocalContext(Context.java:168)
at org.apache.click.extras.control.MenuFactory.loadFromMenuXml(MenuFactory.java:495)
at org.apache.click.extras.control.MenuFactory.getRootMenu(MenuFactory.java:302)
at org.apache.click.extras.control.MenuFactory.getRootMenu(MenuFactory.java:255)
at org.apache.click.extras.control.MenuFactory.getRootMenu(MenuFactory.java:197)
at org.test.pages.BasePage.<init>(BasePage.java:15)
at org.test.pages.HomePage.<init>(HomePage.java:24)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126)
... 30 more
This is my applicationContext.xml:
<context:annotation-config />
<context:component-scan base-package="org.test" />
<tx:annotation-driven />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="oracle.jdbc.OracleDriver" />
<property name="jdbcUrl" value="jdbc:oracle:thin:#192.168.0.10:1521:xe" />
<property name="user" value="HR" />
<property name="password" value="hr"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ctest" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
This is my web.xml:
<display-name>CTest</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>ClickServlet</servlet-name>
<servlet-class>org.apache.click.extras.spring.SpringClickServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ClickServlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
Edit: I changed the code as suggested but my dao is still null.
Also at the appContext I put:
<context:component-scan base-package="org.test.pages" scope-resolver="org.apache.click.extras.spring.PageScopeResolver"/>
Ok, I tried to inject my Dao in my IndexPage but in the constructor cTestDao is null.
What am i doing wrong?
Thanks
IndexPage class code:
#Component #Scope("prototype")
public class IndexPage extends Page {
#Resource
protected CTestDao<Employee> cTestDao;
public IndexPage(){
super();
List<Employee> list = cTestDao.getBeans(Employee.class);
for(Employee e:list){
String s = String.format("Name:%1 Last Name:%2 Salary%3€",e.getFirstName(),e.getLastName(),e.getSalary());
System.out.println(s);
}
}
}
This sounds completely unrelated to Spring, as your stacktrace shows the exception coming from org.apache.click classes.
What does org.test.pages.BasePage do?
I'd suggest trimming down your code to something simple like outputting "Hello World" to test the Spring configuration and context, and then adding other libraries you'd like to use in your webapp.
This doesn't really have anything to do with Spring. Your HomePage class is calling a method on a Click API which it apparently isn't allowed to do.
I suggest you not try to kill two birds with one stone. It's hard enough learning one framework at a time without trying to learn two at the same time, since you'll forever be trying to figure out what's going wrong.
I suggest taking Spring out of the equation, and get yourself comfortable with Click first. Or vice versa.
Click Framework docs suggest to use scope = "prototype" for pages. If you use annotation-based configuration, it will be:
#Component #Scope("prototype")
It seems as if you want to treat Click pages like Spring beans, in other words you want Spring to create your Click page and inject the dependencies. Spring supports two types of dependency injection: through setter methods and constructor. In your example above you are accessing the dao in your Page constructor, but the dao can only be injected after the page has been constructed.
I suggest you move your code into the Page onInit() method.
Alternatively you could inject the DAO into the Page constructor "IndexPage(CTestDao dao)", but I haven't tested whether that will work or not.
Kind regards
Bob