Spring Autowired Services Set on Deploy, but Null when called - java

Sorry if I mess up with my question, I am just getting started configuring MVC, Spring, etc....
The issue that I am running into is that in my Spring MVC project all of my Autowired services are being successfully autowired when my application deploys (verified by setting breakpoints in Spring Tool Suite), but when I try to invoke a autowired service's method I run into a NullPointerException. I have looked all over at different configuration files and it seems like my servelt-context, root-context and web XML files should be ok (don't quote me on that and they are included below).
I am wondering if somehow I am not invoking the instance of the service created at deploy time? It seems strange that the Autowired setters can be called successfully but then the services end up being null. Any help you can provide is greatly appreciated!
root-context.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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.byteslounge.spring.tx.model" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDrive" />
<property name="url"
value="jdbc:oracle:thin:#**********" />
<property name="username" value="*******" />
<property name="password" value="*******" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.clm.billing" />
servelt-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<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>
</beans:beans>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</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>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>OrderList</display-name>
<servlet-name>OrderList</servlet-name>
<servlet-class>com.clm.billing.Oracle.OrderList</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OrderList</servlet-name>
<url-pattern>/OrderList</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>EditBilling</display-name>
<servlet-name>EditBilling</servlet-name>
<servlet-class>com.clm.billing.EditBilling</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EditBilling</servlet-name>
<url-pattern>/EditBilling</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>UpdateBilling</display-name>
<servlet-name>UpdateBilling</servlet-name>
<servlet-class>com.clm.billing.UpdateBilling</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateBilling</servlet-name>
<url-pattern>/UpdateBilling</url-pattern>
</servlet-mapping>
</web-app>
InsuranceNoteDBServiceImpl:
(Here the setiNoteDAO is called with a instance of the iNoteDAO class, but when getNoteById is called iNoteDAO is null)
#Service
public class InsuranceNoteDBServiceImpl implements InsuranceNoteDBService {
private InsuranceNoteDAO iNoteDAO;
#Autowired
public void setiNoteDAO(InsuranceNoteDAO iNoteDAO) {
this.iNoteDAO = iNoteDAO;
}
#Override
#Transactional
public void insertNote(BillerNote note) {
iNoteDAO.insertNote(note);
}
#Override
#Transactional
public BillerNote getNoteById(int noteId) {
return iNoteDAO.getNoteById(noteId);
}
}
InsuranceNoteDBService:
public interface InsuranceNoteDBService {
void insertNote(BillerNote note);
BillerNote getNoteById(int noteId);
}
InsuranceNoteDAOImpl:
(Same thing happens here with the init() method that is setting the session factory)
#Service
public class InsuranceNoteDAOImpl implements InsuranceNoteDAO {
public SessionFactory sessionFactory;
#Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
#Override
public void insertNote(BillerNote note) {
sessionFactory.getCurrentSession().save(note);
}
#Override
public BillerNote getNoteById(int noteId) {
return (BillerNote) sessionFactory.
getCurrentSession().
get(BillerNote.class, noteId);
}
}
InsuranceNoteDAO:
public interface InsuranceNoteDAO {
void insertNote(BillerNote note);
BillerNote getNoteById(int noteId);
}

Remove the init method and annotate the setter :
#Autowired
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}

Related

getting null value when using #Value injection in class annotated by #Service but able to get values in class annotated by #Controller

I am getting null value when trying to inject it using #Value injection in clas annotated by #Service Class but i am able to get values for same properties in class annotated by #Service
I am using Spring 4.2 vesion
web.xml is as follow:::
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name></display-name>
<servlet>
<servlet-name>CaptchaServlet</servlet-name>
<servlet-class>com.cdac.sikkimSprings.servlets.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CaptchaServlet</servlet-name>
<url-pattern>/captcha.jpg</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SpringController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/beans.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springMVC.xml is as follow
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.basePackage" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:property-placeholder location="classpath:properties/development.properties" order="1"/>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
i also have beans.xml for bean definitions which is as follow
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property
name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username"
value="root" /> <property name="password" value="password" /> </bean> -->
//Bean definition mentioned below is the same class where i need the property values to be injected
which is annotated by #Service annotation
<bean id="userManagement"
class="com.basepackage.userManagement">
</bean>
</beans>
Below is actual java class where values are needed to be injected
#Service("userManagementService")
#Transactional
public class userManagement implements RetrieveUserListService{
//This value is not getting injected
#Value("${registrationstatus_registered}")
String statusRegistered;
#Value("${registrationstatus_pending}")
String statusPending;
#Override
public List<ShowUserListPOJO> RetrieveUserList(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
//here the required value is null
System.out.println(statusRegistered);
return null;
}
//Code bellow is skipped...
Same values i am injecting in class below here they are injected properly
#Controller
public class UserManagement {
#Value( "${registrationstatus_registered}" )
String registrationstatus;
#RequestMapping(value="/userManagement", method = RequestMethod.GET)
public void userManagement(HttpServletRequest request,HttpServletResponse response) {
//here value is prnted properly
System.out.println(registrationstatus);
//......Code below skipped
}
development.properties is as follow
registrationstatus_registered = registered
registrationstatus_pending = pending
In your application you have two spring contexts: root application context (ContextLoaderListener) and web application context(DispatcherServlet). You need to understand the difference between them. Read here .
If you move your property resource definition to beans.xml(which is used for root context), your property value will be injected correctly throughout the application.
move this bean difinition to beans.xml
<context:property-placeholder location="classpath:properties/development.properties" order="1"/>.

Thymeleaf template/ view not found - Spring 4

I'm setting up a new SPring4 app using Thymeleaf and keep encountering the same issue when it comes to returning the view. I've searched don here and followed some online tutorials but the same error so I'm thinking it may be due to configuration, any help is appreciated, thanks.
The error : org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
And then my config is:
Web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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</param-value>
</context-param>
<!-- Use the simplified configuration by default. -->
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>simple</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>spring.profiles.default</param-name>
<param-value>simple</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<display-name>Test Web Application</display-name>
mcv.xml:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven/>
<!--Allows for static content to easily be served up without needing a controller etc-->
<mvc:resources mapping="/images/**" location="/assets/img/"/>
<mvc:resources mapping="/css/" location="/assets/css/"/>
<mvc:resources mapping="/assets/**" location="/assets/"/>
<!--taken from the thymeleaf site-->
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="cacheable" value="false" />
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
</beans>
rootcontext.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"
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.xsd">
<import resource="mvc.xml" />
<!--double asterisk allows for recursive search - load all under the pacakge-->
<context:component-scan
base-package="
com.example.*"/>
<context:property-placeholder location="classpath:application.properties"/>
</beans>
Edit:
Controller:
#Controller //restcontroller is not meant to be for returning view, but instead the data http://stackoverflow.com/questions/33062509/returning-view-from-spring-mvc-restcontroller
#EnableAutoConfiguration
public class EmrController {
#Autowired EmrService emr;
#ModelAttribute("emrClusterList")
private List<EmrCluster>getAllClusters(){ return emr.getRunningClusters(); }
#RequestMapping(value = "/EmrClusters", method = RequestMethod.GET)
public String displayEmrList(Model model){
model.addAttribute("emrClusterList", emr.getRunningClusters());
return "index";
}

#ServerEndpoint and Spring MVC injection

I am trying to inject annotated by #Repository class in #ServerEndpoint class. But when i am trying to call repository method it is return null. Another injected bean from this package is working fine.
#ApplicationScoped
#ServerEndpoint("/WebsocketHome/actions")
public class WebSocketServer {
private static final Logger LOG = Logger.getLogger(WebSocketServer.class);
#Inject
private SessionHandler sessionHandler;
#Inject
private PlaceRepository placeRepository;
#OnMessage
public void handleMessage(String message, Session session) {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(message);
if ("getRooms".equals(jsonObject.get("action"))) {
List<Place> places = this.placeRepository.getAllPlaces(); //error is here
}
} catch (ParseException e) {
LOG.error(e.getMessage());
}
.....
This is repository class:
#Repository
#Transactional
public class PlaceRepository {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<Place> getAllPlaces() {
return this.sessionFactory.getCurrentSession().createQuery("from Place place").list();
}
}
web.xml:
<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">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
app-context.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:application.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="com.hms.repository"/>
<context:component-scan base-package="com.hms.utils"/>
<tx:annotation-driven transaction-manager="txManager"/>
<import resource="security-context.xml"/>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driverClassName}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<!--
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
<property name="minIdle" value="2" />
-->
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">${db.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
</beans>
Error appears only on calling of #OnMessage method.
All junit #Tests of repository class returns fine results.
What is wrong in my code?
Sorry for my english.
UPD:
It seems, that problem is in SessionFactory dependency because test method, that i add in #Repository:
public String testWS() {
return "Test is ok!";
}
returns fine result.
So, looks like i found the right way. I found it in Spring websocket documentation.
There are some steps what i did:
I put in type-level annotation:
#ServerEndpoint(value = "/WebsocketHome/actions", configurator = SpringConfigurator.class)
I added #Service and #Controller to my websocket classes and "context:component-scan" path to my app-context.xml file so that Spring can find corresponding beans.
I added the "spring-websocket" dependency in my pom.xml (i use maven)
Maybe it is not the right way, but it is works fine for me.
#Today jan 31' 2022 Just Add "spring-websocket" dependency

Spring #Autowired throwing Null pointer exception when overriding retrieveUser() method of Spring security

I have a spring application which implemented spring security.I was trying to overide method UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken pWord){} by extending my LoginController with AbstractUserDetailsAuthenticationProvider
In this Class I used #Autowired annotation like
#Autowired
private UserManager userManager;
Unfortunately userManager is null inside retrieveUser method
Following is My code:
LoginController.java
package com.springmaster.controller;
...
....
#Controller
public class LoginController extends AbstractUserDetailsAuthenticationProvider {
#Autowired
private UserManager userManager;
/**
* #return the userManager
*/
public UserManager getUserManager() {
return userManager;
}
/**
* #param userManager the userManager to set
*/
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
System.out.println("----------"+this.userManager); //getting not null here
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
#Override
protected void additionalAuthenticationChecks(UserDetails arg0,
UsernamePasswordAuthenticationToken arg1)
throws AuthenticationException {
// TODO Auto-generated method stub
}
#Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken pWord)
throws AuthenticationException {
String password = (String) pWord.getCredentials();
UserManager userManager = new UserManagerImpl();
System.out.println("----------"+this.userManager); //getting null here
List <UserEntity> userEntities= userManager.getAllUsers(username);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_Admin"));
return new User(username, password, true, // enabled
true, // account not expired
true, // credentials not expired
true, // account not locked
authorities);
}
}
Spring-servlet.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.springmaster.*" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}"></bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="userProfile" class="com.springmaster.entity.UserProfileEntity"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_Admin" />
<form-login login-page="/login" default-target-url="/admin"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>
<!-- Configure Authentication mechanism -->
<beans:bean id="CustomAuthenticationProvider" class="com.springmaster.controller.LoginController">
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="CustomAuthenticationProvider" />
</authentication-manager>
</beans:beans>
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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- -->
<!-- needed for ContextLoaderListener -->
<!-- <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/springmaster/applicationContext.xml</param-value>
</context-param>
-->
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Loads Spring Security config file -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Some research gave a brief idea about it like
web.xml is creating two Spring application contexts. Let's call them Security (after security-context.xml) and Servlet (after servlet-context.xml). Security is created by the ContextLoaderListener listener, and Servlet is created by the DispatcherServlet servlet. Security is the parent of Servlet. That means that the beans in Security are only visible to other beans in Security, and the beans in Servlet can see both the beans in Security and in Servlet.
As a beginner can any one tell me what all configuration I should do in configuration files to overcome this barrier
Any Help will be highly appreciated
Thanks in advance

Spring #Autowired Field - NoSuchBeanDefinitionException

I realize this question has been asked many times, but those answers don't seem to get me working.
The class which has the #Autowired field:
#Component
public class SpecialClaimsCaseManager {
#Autowired
private SpecialClaimsCaseRepositoryService<SpecialClaimsCaseDto> service;
public SpecialClaimsCaseManager() {
}
public Collection<SpecialClaimsCase> findAll() {
return convertToSpecialClaimsCase(service.findAll());
}
The interface SpecialClaimsCaseRepositoryService
public interface SpecialClaimsCaseRepositoryService<C extends SpecialClaimsCaseDto> {
//Some method signatures, not relevant
The implementation class (what should be injected)
#Service("specialClaimsCaseRepositoryService")
public class SpecialClaimsCaseRepositoryServiceImpl implements SpecialClaimsCaseRepositoryService<SpecialClaimsCaseDto> {
//Some method implementations, not relevant
mvcDispatcher.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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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="com.redacted.sch"/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpecialClaimsHandling</display-name>
<!-- Spring Configuration Files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/application-security.xml
classpath*:sch_model_spring.xml
</param-value>
</context-param>
<!-- Spring Security Filters -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring Listeners -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- MVC Filter -->
<servlet>
<servlet-name>mvcDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvcDispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Session Configuration -->
<session-config>
<session-timeout>5</session-timeout>
</session-config>
</web-app>
sch_model_spring.xml (in another project)
<?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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.redacted.sch.model"/>
<tx:annotation-driven />
<tx:jta-transaction-manager />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="redacted" />
<property name="username" value="redacted" />
<property name="password" value="redacted" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="schManager" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
Full stack trace (fpasted because it's pretty long) http://fpaste.org/116696/14049194/
So, as we can see, mvc:annotation-driven is enabled, and autowiring is enabled. If I understand this correctly (I might not, pretty new to Spring), this should be all I need. SpecialClaimsCaseRepositoryService is an interface, if that matters, though I don't think it should as this same #Autowiring worked fine in another class annotated with #Controller.
Thanks for any help!
You'll notice from your stack trace that the exception occurs in the process of initializing the root application context loaded by the ContextLoaderListener. That's taken from
<!-- Spring Configuration Files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/application-security.xml
classpath*:sch_model_spring.xml
</param-value>
</context-param>
In those two, you are scanning
<context:component-scan base-package="com.redacted.sch.model"/>
but not the com.redacted.sch.service... package that is required by one of the beans.
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.redacted.sch.service.SpecialClaimsCaseRepositoryService com.redacted.sch.model.SpecialClaimsCaseManager.specialClaimsCaseRepositoryService;
In this case, xyz.model.SpecialClaimsCaseManager has an #Autowired field of type xyz.service.SpecialClaimsCaseRepositoryService, but no such bean exists.
Don't mix component-scanned folders between application contexts, those loaded by ContextLoaderListener vs DispatcherServlet. Refactor so that application beans are loaded by the ContextLoaderListener and controller-related beans are loaded by the DispatcherServlet.
Reading:
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Categories

Resources