Hi i am trying to test my DaoTest class as a junit test.While running the class I get:
java.lang.NoClassDefFoundError:
org/springframework/beans/factory/NoUniqueBeanDefinitionException.
I looked upon the internet and found out that this might be due to more than onre reference to your beans in the configuration file. But i am not able to figure out how do i have more than one reference to the beans.
Here is UserDaoTest class:
#ContextConfiguration (locations = "classpath:persistence-beans.xml")
public class UserDaoTest extends DomainAwareBase {
#Autowired
#Qualifier("userDao")
private UserDao userDao;
#Test
public void testUpdate() {
int size = userDao.list().size();
User user = new User(1, "jimmy", "password", "admin", "sales");
userDao.add(user);
Assert.assertTrue(size < userDao.list().size());
}
#Test
public void testFind() {
User user = new User(1, "jimmy", "password", "admin", "sales");
userDao.add(user);
User found = userDao.find(user.getUserId());
Assert.assertEquals(user, found);
}
#Test
public void testList() {
Assert.assertEquals(0, userDao.list().size());
User user1 = new User(1, "jimmy", "password", "admin", "Sales");
User user2 = new User(2, "pankit", "pankit", "admin", "HR");
User user3 = new User(3, "abc", "abc", "admin", "Engineer");
List<User> users = Arrays.asList(user1, user2, user3);
for (User user : users) {
userDao.add(user);
}
List<User> found = userDao.list();
Assert.assertEquals(3, userDao.list().size());
for (User user : found) {
Assert.assertTrue(users.contains(user));
}
}
#Test
public void testRemove() {
User user1 = new User(1, "jimmy", "password", "admin", "Sales");
userDao.add(user1);
Assert.assertEquals(user1, userDao.find(user1.getUserId()));
userDao.remove(user1);
Assert.assertNull(userDao.find(user1.getUserId()));
}
}
and this is my persistence-beans.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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- we can use annotations -->
<context:annotation-config />
<!-- package to look for annotated classes -->
<context:component-scan base-package="com.finalproject" />
<!-- we will manage transactions with annotations -->
<tx:annotation-driven />
<!-- data source for our database -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<property name="url"
value="jdbc:mysql://localhost:3306/leadmanagement_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- configure hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
EDIT
This is my stack trace
java.lang.NoClassDefFoundError: org/springframework/beans/factory/NoUniqueBeanDefinitionException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getDeclaredMethods(Class.java:1808)
at org.springframework.core.type.StandardAnnotationMetadata.hasAnnotatedMethods(StandardAnnotationMetadata.java:159)
at org.springframework.context.annotation.ConfigurationClassUtils.isLiteConfigurationCandidate(ConfigurationClassUtils.java:106)
at org.springframework.context.annotation.ConfigurationClassUtils.checkConfigurationClassCandidate(ConfigurationClassUtils.java:87)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:233)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:203)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.NoUniqueBeanDefinitionException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 41 more
Class NoUniqueBeanDefinitionException is not present in your classpath. Include spring-beans dependency/jar into your test classpath and try again.
Related
I am upgrading Spring framework from very old version to 5.3 - I made updated to controller and configuration file. I am getting "javax.servlet.ServletException: No adapter for handler for Controller" error.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:oxm="http://www.springframework.org/schema/oxm"
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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<context:component-scan base-package="abc.controller,abc.bean,abc.bean.command,abc.validator" />
<context:annotation-config />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<!-- Controllers -->
<bean id="uploadFormController" class="abc.controller.UploadFormController">
<property name="mailSender"><ref bean="mailSender"/></property>
<property name="message"><ref bean="uploadConfirmationEmail"/></property>
<property name="submissionDao"><ref bean="submissionDao"/></property>
<property name="providerDao"><ref bean="providerDao"/></property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
</property>
<property name="interceptors">
<list>
<ref bean="securityInterceptor"/>
</list>
</property>
<property name="mappings">
<props>
<prop key="upload.html">starSiSpreadsheetUploadFormController</prop>
</props>
</property>
</bean>
<bean id="securityInterceptor"
class="abc.interceptor.SecurityInterceptor">
<property name="defaultUser"><value>${abc.defaultUser}</value></property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix"><value>/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>`
package abc.controller;
#Controller
#RequestMapping("/upload.html")
public class UploadFormController {
#Autowired
private SpreadsheetUpload bean; //CommandClass
#Autowired
private MailSender mailSender;
#Autowired
private SimpleMailMessage message;
#Autowired
private SubmissionDAO submissionDao;
#Autowired
private ProviderDAO providerDao;
protected String onSubmit(HttpServletRequest request,
HttpServletResponse response, BindException errors)
throws Exception
{
// let's see if there's a provider
if (bean.getProvider() == null)
{
log.info("No provider selected.");
throw new DataEntryException("No provider selected. ");
}
return "redirect:upload.html";
}
protected Map referenceData(HttpServletRequest request) throws Exception
{
// TODO - switch code over to using LDAP queries
HttpSession session = request.getSession();
//Logic goes here..
Map map = new HashMap();
map.put("admin", admin);
return map;
}
}
Could someone take a look and help me on this? I have been trying since last two days and no luck so far. Thank you!
There is nothing wrong in my code. I have another method called "OnSubmit" which is causing the problem.
I am writing a simple process application using Spring MVC and Camunda with a shared process engine. Now I want to add simple test cases and I am running into the problem that the process engine returns null for every factory method. When running the application the process engine returns the services as expected.
How should i configure camunda for JUnit tests, when using a shared process engine?
This is my camunda process engine configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bind the process engine service as Spring Bean -->
<bean name="processEngineService" class="org.camunda.bpm.BpmPlatform" factory-method="getProcessEngineService" />
<!-- bind the default process engine as Spring Bean -->
<bean name="processEngine" factory-bean="processEngineService" factory-method="getDefaultProcessEngine" />
<bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
<bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
<bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
<bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
<bean id="managementService" factory-bean="processEngine" factory-method="getManagementService"/>
<bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService"/>
<bean id="authorizationService" factory-bean="processEngine" factory-method="getAuthorizationService"/>
<!-- bootstrap the process application -->
<bean id="processApplication" class="org.camunda.bpm.engine.spring.application.SpringServletProcessApplication" />
</beans>
and this is the releavant part of my simple test class:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration({
"file:src/main/webapp/WEB-INF/process-conf.xml",
"file:src/main/webapp/WEB-INF/hibernate-conf.xml",
"file:src/main/webapp/WEB-INF/camunda-conf.xml",
"file:src/main/webapp/WEB-INF/dispatcher-servlet.xml",
})
public class OrderControllerTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
#Test
public void testTest() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/");
this.mockMvc.perform(builder)
.andExpect(ok);
}
}
This is the exception that is thrown when starting the junit test:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'repositoryService' defined in URL [file:src/main/webapp/WEB-INF/camunda-conf.xml]: factory-bean 'processEngine' (or a BeanPostProcessor involved) returned null
I solved the problem via a workaround based on a guess:
It seems that the tests are rund directly in java, without the tomcat server instance. Therefore there is no shared process engine which can be accessed.
The solution:
I created another camunda configuration for an embedded process engine which uses the same database as the shared engine that is configured in the tomcat instance. The process engine can be instantiated then and the test is running fine. My guess is that one should be cautious to not have tomcat and the test run concurrently.
this is the embedded process engine configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/CamundaProcessEngine_001?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"/>
<property name="username" value="####"/>
<property name="password" value="####"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="processEngineConfiguration" class="org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseSchemaUpdate" value="true" />
<property name="jobExecutorActivate" value="false" />
<!-- turn off metrics reporter -->
<property name="dbMetricsReporterActivate" value="false" />
<property name="history" value="full" />
</bean>
<bean id="processEngine" class="org.camunda.bpm.engine.spring.ProcessEngineFactoryBean">
<property name="processEngineConfiguration" ref="processEngineConfiguration" />
</bean>
<bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
<bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
<bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
<bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
<bean id="managementService" factory-bean="processEngine" factory-method="getManagementService"/>
<bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService"/>
<bean id="authorizationService" factory-bean="processEngine" factory-method="getAuthorizationService"/>
<bean id="activitiRule" class="org.camunda.bpm.engine.test.ProcessEngineRule">
<property name="processEngine" ref="processEngine" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Recently I have started a new project and decided to use the latest versions of spring, spring security and thymeleaf
I have included these packets
def springVersion = '4.1.6.RELEASE'
def securityVersion = '4.0.1.RELEASE'
def thymeleafVersion = '2.1.2.RELEASE'
compile "org.springframework:spring-core:$springVersion"
compile "org.springframework:spring-webmvc:$springVersion"
compile "org.springframework.security:spring-security-web:$securityVersion"
compile "org.springframework.security:spring-security-config:$securityVersion"
compile "org.thymeleaf:thymeleaf-spring4:$thymeleafVersion"
compile "org.thymeleaf.extras:thymeleaf-extras-springsecurity4:$thymeleafVersion"
I have added #EnableWebSecurity and #Bean SpringSecurityDialect to my configuration.
In the layout.html I have
<ul class="nav navbar-nav navbar-right">
<li sec:authorize="isAnonymous()"><a th:href="#{/login}">Login</a></li>
<li sec:authorize="isAuthenticated()"><a th:href="#{/logout}">Logout</a></li>
</ul>
<br>
Neither of the options show up. Moreover, when I replace those calls with true that doesn't change anything. And I don't see any error messages when make an error in function name like isAnon().
Am I missing something?
UPD
Security config
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin()
.loginPage("/login")
.failureUrl("/login-error")
.and()
.logout()
.logoutSuccessUrl("/")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
}
Web config
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"stats.web.controller","stats.web.domain","stats.mapper", "stats.core.service;"})
#Import({ WebSecurityConfig.class })
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
#Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en"));
return cookieLocaleResolver;
}
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setCacheable(false);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addDialect(securityDialect());
engine.setTemplateResolver(templateResolver());
return engine;
}
#Bean
public SpringSecurityDialect securityDialect() {
return new SpringSecurityDialect();
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
viewResolver.setViewNames(new String[]{"*"});
viewResolver.setCache(false);
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(0);
return messageSource;
}
}
Not sure what bootstrap classes are needed, but I've inspected the page, the second ul that supposed to have login link is empty:
<ul class="nav navbar-nav">
::before
<li>...</li>
<li>...</li>
<li>...</li>
::after
</ul>
<ul class="nav navbar-nav navbar-right">
::before
::after
</ul>
Here is the XML config as I said. Kindly remove the files which you have, annotate your methods to #Service, #Repository for DAO, #Controller for Controller and #Entity for model. PLease dont forget #Transactional. I am authenticating against a DB in postgreSQL, but you can change the dialect.
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"
>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml,/WEB-INF/spring/appServlet/security-applicationContext.xml</param-value>
</context-param>
<session-config>
<session-timeout>1440</session-timeout>
</session-config>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>403Jsp</servlet-name>
<jsp-file>/WEB-INF/views/error/403.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>403Jsp</servlet-name>
<url-pattern>/403</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Servlet-context.xml :
<security:global-method-security
secured-annotations="enabled"
jsr250-annotations="disabled"
pre-post-annotations="enabled"/>
<context:component-scan base-package="com.journaldev.spring" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:property-placeholder location="classpath:application.properties"/>
<mvc:annotation-driven>
<mvc:argument-resolvers>
<beans:bean class="org.springframework.mobile.device.DeviceWebArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
<mvc:interceptors>
<beans:bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor"/>
<beans:ref bean="localeChangeInterceptor" />
</mvc:interceptors>
<mvc:default-servlet-handler/>
<resources mapping="/resources/" location="/resources/"/>
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/"/>
<beans:property name="suffix" value=".jsp"/>
</beans:bean>
<!-- If you have locale and all, then you need code below -->
<!-- locale -->
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="classpath:/locale/messages"/>
<beans:property name="defaultEncoding" value="UTF-8"/>
</beans:bean>
<!-- default locale -->
<beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<beans:property name="defaultLocale" value="de"/>
</beans:bean>
<!-- Change locale via url. -->
<beans:bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<beans:property name="paramName" value="lang"/>
</beans:bean>
<beans:bean id="handlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<beans:property name="interceptors">
<beans:list>
<beans:ref bean="localeChangeInterceptor"/>
</beans:list>
</beans:property>
</beans:bean>
</beans:beans>
root-context.xml :
<context:component-scan base-package="com.journaldev.spring">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:property-placeholder location="classpath:application.properties"/>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="org.postgresql.Driver"/>
<beans:property name="url"
value="jdbc:postgresql://localhost:5432/dbname"/>
<beans:property name="username" value="postgres"/>
<beans:property name="password" value="dbpass"/>
<beans:property name="removeAbandoned" value="true"/>
<beans:property name="removeAbandonedTimeout" value="20"/>
<beans:property name="defaultAutoCommit" value="false"/>
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="packagesToScan" value="com.journaldev.spring.model" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</beans:prop>
<beans:prop key="hibernate.show_sql">false</beans:prop>
<!-- <beans:prop key="hibernate.jdbc.batch_size">1000</beans:prop>
<beans:prop key="hibernate.order_updates">true</beans:prop>-->
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="LoginServiceImpl" class="com.journaldev.spring.service.LoginServiceImpl"/>
<task:annotation-driven/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</beans:bean>
</beans:beans>
security-applicationContext.xml :
<security:http pattern="/resources/**" security="none"/>
<security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
<security:form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/dashboard" always-use-default-target="false" authentication-failure-url="/denied" />
<security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
<security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<security:port-mappings>
<security:port-mapping http="80" https="443"/>
</security:port-mappings>
<security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>
<security:session-management session-fixation-protection="migrateSession">
<security:concurrency-control session-registry-ref="sessionRegistry" max-sessions="5" expired-url="/login"/>
</security:session-management>
</security:http>
<!-- Rest authentication, don't edit, delete, add-->
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain filters="persistencefilter,authenticationfilter" pattern="/login"/>
<security:filter-chain filters="persistencefilter,logoutfilter" pattern="/logout"/>
<security:filter-chain pattern="/rest/**" filters="persistencefilter,restfilter" />
</security:filter-chain-map>
</bean>
<bean id="persistencefilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>
<bean id="authenticationfilter" class="com.journaldev.spring.utility.AuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
<property name="passwordParameter" value="pass"/>
<property name="usernameParameter" value="user"/>
<property name="postOnly" value="false"/>
</bean>
<bean id="myAuthSuccessHandler" class="com.journaldev.spring.utility.AuthenticationSuccessHandler"/>
<bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>
<bean id="logoutfilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg index="0" value="/"/>
<constructor-arg index="1">
<list>
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
<property name="invalidateHttpSession" value="true"/>
<property name="clearAuthentication" value="true"/>
</bean>
<bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>
</list>
</constructor-arg>
</bean>
<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
</list>
</property>
</bean>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>
<bean id="restfilter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
<property name="securityMetadataSource">
<security:filter-invocation-definition-source>
<security:intercept-url pattern="/rest/**" access="ROLE_USER"/>
</security:filter-invocation-definition-source>
</property>
</bean>
<!-- Rest authentication ends here-->
<!-- queries to be run on data -->
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<beans:property name="key" value="_spring_security_remember_me" />
<property name="alwaysRemember" value="true"/>
<beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
<beans:property name="userDetailsService" ref="LoginServiceImpl"/>
</beans:bean>
<!--Database management for remember-me -->
<beans:bean id="jdbcTokenRepository"
class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<beans:property name="createTableOnStartup" value="false"/>
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<!-- Remember me ends here -->
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="LoginServiceImpl">
<security:password-encoder ref="encoder"/>
</security:authentication-provider>
</security:authentication-manager>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="LoginServiceImpl"/>
<beans:property name="passwordEncoder" ref="encoder"/>
</beans:bean>
</beans>
For your reference : The only bean LoginServiceImpl bean I have explicitly declared for login :
#Transactional
#Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{
#Autowired private PersonDAO personDAO;
#Autowired private Assembler assembler;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
Person person = personDAO.findPersonByUsername(username.toLowerCase());
if(person == null) { throw new UsernameNotFoundException("Wrong username or password");}
return assembler.buildUserFromUserEntity(person);
}
public LoginServiceImpl() {
}
}
To use my code, you need to add the xml files, I hope you can add the schema mappings on your own, if not, I will paste them. When you are done creating and adding code in XML files, please correct package name to LoginServiceImpl, and in web.xml, point the security-applicationContext.xml and root-context.xml correctly.
Any helpp you need lemme know. And the above configuration is tweaked by M.Denium, so incase I am not there on weekend as I am travelling and he is free, he can help you. Have fun. :-)
It might help to compare your configuration with Spring Boot autoconfiguration for Thymeleaf.
Also, I vaguely remember having similar issue that I resolved by moving sec:authorize in <ul> (instead of <li>). It's been a while, so I don't remember the reason I moved it like that. (Sorry!) Here's a sample of what worked for me (although it was with org.thymeleaf.extras:thymeleaf-extras-springsecurity3).
<ul sec:authorize="isAuthenticated()">
<li><p><span sec:authentication="name">test</span></p> </li>
<li>Logout </li>
</ul>
<ul sec:authorize="isAnonymous()">
<li>Sign Up </li>
<li>Login </li>
</ul>
Finally, I have found the difference with my working spring 3 project. It wasn't the spring version, it was this missing class
public class SpringSecurityInitializer extends
AbstractSecurityWebApplicationInitializer {
}
After I added it the "sec" attributes works correctly.
I am working with Spring MVC. My application was ok before inserting tiles, now I keep receiving the error message as:
javax.servlet.ServletException: Could not resolve view with name '/sisStudent' in servlet with name 'mvc-dispatcher'
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1190)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
My tiles.xml is:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/jsp/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/jsps/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/jsps/menu.jsp" />
<put-attribute name="body" value="" />
<!-- put-attribute name="footer" value="/WEB-INF/jsps/footer.jsp" /> -->
</definition>
<definition name="sisStudent" extends="base.definition">
<put-attribute name="title" value="SIS Students" />
<put-attribute name="body" value="/WEB-INF/jsps/sisStudent.jsp" />
</definition>
</tiles-definitions>
My spring-servlet.xml is:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="au.edu.nsw.det.tls.tar.sis.controller" />
<!--
bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
property name="prefix"> <value>/WEB-INF/jsps/</value> </property>
<property name="suffix"> <value>.jsp</value> </property> <property
name="viewClass"> <value>
org.springframework.web.servlet.view.tiles3.TilesView</value>
</property> </bean>
-->
<!-- bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsps/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value> org.springframework.web.servlet.view.tiles3.TilesView</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
My controller is:
#Controller
// #RequestMapping("/studentSearch")
public class StudentSearchController {
#Autowired
StudentService studentService;
// #RequestMapping(value="/StudentSearchById", method = RequestMethod.GET)
// public ModelAndView searchById(#PathVariable Long studentId) {
#RequestMapping (value="/openStudentSearchScreen", method = RequestMethod.GET)
public ModelAndView openCourseSearchScreen(){
ModelAndView modelAndView = new ModelAndView("/sisStudent");
return modelAndView;
}
}
Any ideas?
Thank you in advance!
In your ModelAndView constructor remove the leading / so it should be
#RequestMapping (value="/openStudentSearchScreen", method = RequestMethod.GET)
public ModelAndView openCourseSearchScreen(){
ModelAndView modelAndView = new ModelAndView("sisStudent");
return modelAndView;
}
OTOH Insted of ModelAndView you can use String
#RequestMapping (value="/openStudentSearchScreen", method = RequestMethod.GET)
public String openCourseSearchScreen(){
return "sisStudent";//Tiles definition name
}
If you want to add some model attribute
#RequestMapping (value="/openStudentSearchScreen", method = RequestMethod.GET)
public String openCourseSearchScreen(Model model){
model.addAttribute("<name of the attribute>",<value as object>);
return "sisStudent";//Tiles definition name
}
I am getting the following exception.Its due to the line
Session ss=session.getCurrentSession();
java.lang.NullPointerException
at com.mkyong.common.dao.UserDao.saveUser(UserDao.java:25)
at com.mkyong.common.controller.JSONController.getShopInJSON(JSONController.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
My dao class is as follows.
package com.mkyong.common.dao;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import com.mkyong.common.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
public class UserDao {
private SessionFactory session;
public void setSessionFactory(SessionFactory session){
if(session == null){
throw new IllegalStateException();
}
this.session=session;
}
public int saveUser(User user) {
Session ss=session.getCurrentSession();
System.out.println(user.getUserName());
System.out.println(user.getPassword());
//Session ss=session.getCurrentSession();
ss.save(user);
return 1;
}
}
My config file is as follows:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.mkyong.common.controller" />
<context:annotation-config/>
<mvc:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="SessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.mkyong.common.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="SessionFactory" ref="SessionFactory" />
</bean>
</beans>
Your session is null.You are using getCurrentSession on null .So you are getting NullpointeException here
Your session is not injected in your DAO. Ensure your configuration is correct.
You can inject your session factory in two ways (choose just one)
1) Xml declaration
Here you will declare your userDAO bean in your xml configuration file this way :
<bean id="userDAO" class="com.mkyong.common.dao.UserDAO">
<property name="session" ref="SessionFactory" />
</bean>
I sometimes have issue when the id of my bean start with a Uppercase letter, so I would rename "SessionFactory" by "sessionFactory".
2) With annotations
Here, Spring will scan all packages declared with
<context:component-scan base-package="com.foo.bar" />
and look for Classes annotated with "#Repository", "#Service" or "#Component" in com.foo.bar package. So, Your class UserDAO should be annotated with "#Repository" to be found and your package must be in component-scan to be scanned.
Now Spring will detect your userDAO bean but don't see any bean to inject, so you must annotate your SessionFactory field with "#Autowired", your class must look like this :
#Repository
public class UserDao {
#Autowired
private SessionFactory session;
public void setSessionFactory(SessionFactory session){
if(session == null){
throw new IllegalStateException();
}
this.session=session;
}
...
And your configuration file look like this :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.mkyong.common.controller" />
<context:component-scan base-package="com.mkyong.common.dao" />
<context:annotation-config/>
<mvc:annotation-driven />
...
</beans>