Liferay 6.2 + Spring #Autowired not working in a hook - spring

I am using Spring 4.0.6 with Liferay 6.2. Spring isn't able to inject autowired components in to the hook, object comes as null. I have also tried with spring version 3.1 that comes with liferay. Same code works in portlets but not in hooks.
private ApplicationEventPublisher publisher in ActivityEventPublisher.java is null.
web.xml
<?xml version="1.0"?>
<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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.liferay.portal.kernel.servlet.SecurePluginContextListener</listener- class>
</listener>
<listener>
<listener-class>com.liferay.portal.kernel.servlet.PortletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
</web-app>
ActivityEventPublisher.java
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import connect.activity.solr.document.ActivityData;
#Component
public class ActivityEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public ApplicationEventPublisher getPublisher() {
return publisher;
}
public void setPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void publish(ActivityData data) {
ActivityEvent event = new ActivityEvent(this);
event.setActivityData(data);
this.publisher.publishEvent(event);
}
}
Any help will be much appreciated.
Thanks

Unfortunately, autowired mechanisms are not allowed in hooks, wrappers or startup actions at Liferay.
You can implement an ApplicationContextProvider, it's so easy and useful:
#Component("applicationContextProvider")
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext ctx = null;
public static ApplicationContext getApplicationContext() {
return ctx;
}
#Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
ctx = ac;
}
}
An example of use in a Hook will be the following:
public class PostLoginActionHook extends Action {
// That code "replaces" #Autowired annotation
private final UserProxyService userProxyService = (UserProxyService) ApplicationContextProvider.
getApplicationContext().getBean(UserProxyService.class);
#Override
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
UserVO myCustomUser = userProxyService.getCustomUserByLiferayUser(user.getUserId());
{...}
}
Hope it helps!

Related

spring-session Session implementation not getting CGLIB Enhanced Proxy Bean

I'm attempting to drop spring-session into an existing web application that uses session scoped beans. This application is running on Wildfly 10.1.0.Final
When I run the application uses wildfly's internal session management, everything works fine. Attempting to put in a custom implementation of Spring-Session is losing the session bean information. When I debug the application, there is a call for scopedTarget.userSessionData, however it is of the underlying class UserSessionData, and not the UserSessionData$$EnhancedBySpringCGLIB$$1234 that has the actual data.
configuration-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="userSessionData" scope="session" class="UserSessionData">
<aop:scoped-proxy/>
</bean>
<context:annotation-config />
<bean class="my.MyHttpSessionConfiguration" />
</beans>
This configuration properly creates and registers a springSessionRepositoryFilter using MyHttpSessionConfiguration. However the problem is when MySession object has a session scoped bean of UserSessionData, I get the raw proxied class instance and not the decorated one which has the session values. I was able to verify this by debugging the below SesssionImpl on the #setAttribute method
class UserSessionData {
private String _myValue;
public void setMyValue(String value) {
_myValue = value;
}
public String getMyValue() {
return _myValue;
}
}
final class MySession implements ExpiringSession {
private final MapSession _delegate;
private final Map<String, Object> _delta = new HashMap<>();
private boolean _isNew;
MySession() {
this(new MapSession());
_isNew = true;
flushImmediateIfNecessary();
}
MySession(MapSession session) {
if (session == null) {
throw new IllegalArgumentException("MapSession cannot be null");
}
_isNew = false;
_delegate = session;
}
public boolean isNew() {
return _isNew;
}
#Override
public String getId() {
return _delegate.getId();
}
#Override
public long getCreationTime() {
return _delegate.getCreationTime();
}
#Override
public long getLastAccessedTime() {
return _delegate.getLastAccessedTime();
}
#Override
public void setLastAccessedTime(long lastAccessedTime) {
_delegate.setLastAccessedTime(lastAccessedTime);
flushImmediateIfNecessary();
}
#Override
public void setMaxInactiveIntervalInSeconds(int interval) {
_delegate.setMaxInactiveIntervalInSeconds(interval);
flushImmediateIfNecessary();
}
#Override
public int getMaxInactiveIntervalInSeconds() {
return _delegate.getMaxInactiveIntervalInSeconds();
}
#Override
public boolean isExpired() {
return _delegate.isExpired();
}
#SuppressWarnings("unchecked")
#Override
public <T> T getAttribute(String attributeName) {
return (T) _delegate.getAttribute(attributeName);
}
#Override
public Set<String> getAttributeNames() {
return _delegate.getAttributeNames();
}
#Override
public void setAttribute(String attributeName, Object attributeValue) {
_delegate.setAttribute(attributeName, attributeValue);
putAndFlush(attributeName, attributeValue);
}
#Override
public void removeAttribute(String attributeName) {
_delegate.removeAttribute(attributeName);
putAndFlush(attributeName, null);
}
Map<String, Object> getDelta() {
return _delta;
}
private void putAndFlush(String attr, Object value) {
_delta.put(attr, value);
flushImmediateIfNecessary();
}
private void flushImmediateIfNecessary() {
if (MySessionRepository.this._flushMode == MyFlushMode.IMMEDIATE) {
MySessionRepository.this.save(this);
}
}
}
I feel like I'm missing either a configuration or something because the native WildFly SessionImpl has the correct Enhanced object for serialization when I remove the springSessionRepositoryFilter and let the container handle the session object. Additionally the Spring Controllers have the correct enhanced object. It's just MySession that does not appear to be getting it. Any thoughts?
EDIT:
Looks like the core issue is that my spring-security is using a different version of the proxy class when setting members, so I am not getting them in the MySession object. Attached are the configurations for Spring-Security
public class WebSessionInitializer extends AbstractHttpSessionInitializer {
}
#Configuration
#EnableSpringHttpSession
public class MySessionConfiguration {
#Bean
public SessionRepository sessionRepository() {
return new MySessionRepository();
}
}
<?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="imb"
version="2.5">
<distributable />
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/configuration-spring.xml
</param-value>
</context-param>
The SpringSession filter is correctly added with my implementation. It appears the root problem is when I get into spring-security, it is setting values on a different instance of UserSessionData than the one in the MySession object. When I use #Autowired in MVC Controllers, I get the correct one.
Library Versions:
Spring: 3.2.14
Spring Session: 1.3.2
WildFly 10.1.0.Final

Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext

I am using Spring MVC,google app engine, admin sdk, cloud sql.
I want to access (preferncesDao) dao class into Filter.
Below is my filter
public class NameSpaceGoogleSecurityFilter implements Filter
{
#Autowired
IPreferencesDao preferncesDao;
public void init( FilterConfig filterConfig ) throws ServletException{
SpringUtils.init(filterConfig.getServletContext());
preferncesDao = SpringUtils.getPreferncesDao();
}
}
Below is my SpringUtils class.
public class SpringUtils {
private static ApplicationContext appContext;
private static IPreferencesDao preferncesDao = null;
public static void init(final ServletConfig config) {
init(config.getServletContext());
}
public static void init(final ServletContext context) {
if(appContext==null){
appContext =
(ApplicationContext) context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}
}
public static IPreferencesDao getPreferncesDao() {
if(preferncesDao==null){
preferncesDao=(IPreferencesDao) appContext.getBean("preferncesDao");
}
return preferncesDao;
}
protected SpringUtils() {
throw new UnsupportedOperationException();
}
}
When I start build process, It is throwing below exception
Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext
java.lang.NullPointerException.
Nullpointer at line preferncesDao=(IPreferencesDao) appContext.getBean("preferncesDao");
How can i resolve above error ? is it right way to get dao object into filter ? if not what is correct way.?
It is required to add below tag in web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
That purely indicate that ContextLoaderListener missing.
so add below code in web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
For more details refer this link

Problems with CDI - ( Weld + TomCat7 + JSF )

I'm starting a project with CDI using weld, and am getting the following error when I try to injection:
#Inject
private UserRepository repository;
Console:
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
13:16:22,859 INFO servletWeldServlet:57 - WELD-ENV-001008: Initialize Weld using ServletContainerInitializer
13:16:22,875 INFO Version:151 - WELD-000900: 2.2.5 (Final)
13:16:22,906 INFO Bootstrap:206 - WELD-000101: Transactional services not available. Injection of #Inject UserTransaction not available. Transactional observers will be invoked synchronously.
13:16:22,937 WARN Interceptor:47 - WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled
13:16:22,937 WARN Interceptor:47 - WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled
13:16:23,046 INFO servletTomcat:45 - WELD-ENV-001100: Tomcat 7+ detected, CDI injection will be available in Servlets, Filters and Listeners.
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type UserRepository with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private br.com.controllers.UserController.repository
at br.com.controllers.UserController.repository(UserController.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:372)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:293)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:167)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:531)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
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:745)
EntityManagerFactory.java
package br.com.util;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class EntityManagerFactory {
#PersistenceContext(unitName="default")
private EntityManager em;
#Produces
public EntityManager create() {
return em;
}
public void close(#Disposes EntityManager em) {
em.close();
}
}
Repository.java
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public abstract class Repository<T, I extends Serializable> {
#Inject
protected final EntityManager entityManager;
protected final Class<T> clazz;
protected Repository(EntityManager entityManager) {
this.entityManager = entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
public void refresh(T entity){
entityManager.refresh(entity);
}
public void create(T entity) {
entityManager.persist(entity);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public void destroy(T entity) {
entityManager.remove(entity);
}
public T find(I id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
TypedQuery<T> query = entityManager.createQuery("FROM " + clazz.getName() ,clazz);
List<T> resultList = query.getResultList();
return resultList;
}
}
UserRepositoryImpl.java
package br.com.repositories;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import br.com.models.User;
#Transactional
public class UserRepositoryImpl extends Repository<User, Long >implements UserRepository {
protected UserRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
}
UserController.java
package br.com.controllers;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.repositories.UserRepository;
#Named("userController")
#RequestScoped
public class UserController {
#Inject
private UserRepository repository;
UserController(){
}
#PostConstruct
public void init(){
System.out.println("started");
}
public String getMessage(){
return "test";
}
public void create(){
System.out.println("test method");
}
}
META-INF/beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Manager pathname=""/> <!-- disables storage of sessions across restarts -->
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>
WEB-INF/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_3_0.xsd" version="3.0">
<display-name>wochenbericht</display-name>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<!-- CDI - WELD -->
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
<resource-env-ref>
<resource-env-ref-name>BeanManager</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.inject.spi.BeanManager
</resource-env-ref-type>
</resource-env-ref>
<!-- JSF -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<!-- SESSION TIMEOUT -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- CONTEXT LOCAL -->
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>2</param-value>
</context-param>
<context-param>
<param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
<param-value>/assets</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- SECURITY SETTINGS -->
<security-constraint>
<display-name>Restrict direct access to XHTML files</display-name>
<web-resource-collection>
<web-resource-name>XHTML files</web-resource-name>
<url-pattern>*.xhtml</url-pattern>
</web-resource-collection>
<auth-constraint />
</security-constraint>
My Libs:
antlr-2.7.7.jar
aopalliance.jar
c3p0-0.9.1.jar
cdi-api-1.1.jar
dom4j-1.6.1.jar
EasyCriteria-3.1.0.jar
hibernate-c3p0-4.3.6.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-entitymanager-4.3.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-validator-4.3.0.Final.jar
javassist-3.18.1-GA.jar
javax.inject.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jsf-api-2.2.8.jar
jsf-impl-2.2.8.jar
log4j-1.2.16.jar
postgresql-9.2-1003.jdbc4.jar
slf4j-api-1.6.6.jar
slf4j-jdk14-1.6.6.jar
slf4j-log4j12-1.6.1.jar
validation-api-1.0.0.GA.jar
weld-se-core-2.2.5.Final.jar
weld-servlet-2.2.5.Final.jar
weld-servlet-core-2.2.5.Final.jar
Can anyone help me? thank you!
Your first problem is that UserRepositoryImpl class doesn't have default (empty) constructor, and nither there is #Produces method, so there is no way to instantiate it. Remove EntityManager entityManager from constructors from Repository and UserRepositoryImpl classes.
Change the constructor in Repository to:
protected Repository() {
/// this.entityManager = entityManager; // <= this is already injected by
// #Inject protected final EntityManager entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
Your second problem will be incorrect injection of PersistenceContext. You either need to use EJB (to inject EntityManager via #PersistenceContext) or for web modules use:
#PersistenceUnit(unitName="default")
EntityManagerFactory emf;
...
EntityManager em = emf.createEntityManager();
And your third problem will be transactions - again you either need to switch to EJB, or handle transactions while persisting your beans.
I'd recommend first read the following before coding:
CDI documentation
Contexts and Dependency Injection for Java EE (Tutorial)
JPA (Tutorial)
Managing Entities
#Gas Thanks for you feedback and links, now works, I do not know if it's the best way:
UserRepositoryImpl
package br.com.repositories;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import br.com.models.User;
#Transactional
public class UserRepositoryImpl extends Repository<User, Long >implements UserRepository {
#Inject
protected UserRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
}
Repository
package br.com.repositories;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public abstract class Repository<T, I extends Serializable> {
protected final EntityManager entityManager;
protected final Class<T> clazz;
protected Repository(EntityManager entityManager) {
this.entityManager = entityManager;
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.clazz = clazz;
}
public void refresh(T entity){
entityManager.refresh(entity);
}
public void create(T entity) {
entityManager.persist(entity);
}
public T update(T entity) {
return entityManager.merge(entity);
}
public void destroy(T entity) {
entityManager.remove(entity);
}
public T find(I id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
TypedQuery<T> query = entityManager.createQuery("FROM " + clazz.getName() ,clazz);
return query.getResultList();
}
}
EntityManagerProducer
package br.com.util;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
#ApplicationScoped
public class EntityManagerProducer {
private EntityManagerFactory factory;
public EntityManagerProducer() {
factory = Persistence.createEntityManagerFactory("default");
}
#Produces #RequestScoped
public EntityManager createEntityManager() {
return factory.createEntityManager();
}
public void closeEntityManager(#Disposes EntityManager manager) {
manager.close();
}
}
UserController
package br.com.vw.controllers;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.models.User;
import br.com.repositories.UserRepository;
#Named("userController")
#RequestScoped
public class UserController {
#Inject UserRepository userRepository;
UserController(){
}
#PostConstruct
public void init(){
System.out.println("Inicialilizado o construtor");
}
public String getMessage(){
return "Conteúdo da mensagem";
}
public void create(){
System.out.println("Método create disparado");
User user = new User();
user.setEmail("email#uol.com.br");
user.setName("Marcos de Freitas");
userRepository.create(user);
}
}
Tks

getting empty form session bean in jsf

I have set session bean after login, and print the value from session bean it prints in xhtml file but while i go to the next page or bean session bean return empty it automatically reset the value.
I am using the primeface 4.0, jsf 2.0 and ejb 3.0 for web application.
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">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value> </context-param> -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>ui-lightness</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.CHECK_ID_PRODUCTION_MODE</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.VIEW_UNIQUE_IDS_CACHE_ENABLED</param-name>
<param-value>true</param-value>
</context-param>
<mime-mapping>
<extension>xlsx</extension>
<mime-type>text/xlsx</mime-type>
</mime-mapping>
</web-app>
//Setting user from loginMB having viewscope bean.
UserMB
#SessionScoped
#ManagedBean(name = "userMB")
public class UserMB extends AbstractMB implements Serializable {
public static final String INJECTION_NAME = "#{userMB}";
private static final long serialVersionUID = 1L;
private User user;
#EJB
private UserEJB userEJB;
public String logOut() {
getRequest().getSession().invalidate();
return "/index.xhtml?faces-redirect=true";
}
private HttpServletRequest getRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
}
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
if (userList == null) {
userList = userEJB.findAll();
}
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
CampMB
#ManagedBean
#ViewScoped
public class CampMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{userMB}")
private UserMB userMB;
public UserMB getUserMB() {
return userMB;
}
public void setUserMB(UserMB userMB) {
this.userMB = userMB;
}
private User user;
private Camp camp;
private List<CampDTO> listCamp;
#EJB
private CampEJB campEJB;
#EJB
private MemberEJB memberEJB;
#EJB
private CodeValueEJB codeEJB;
TimeZone timeZone = TimeZone.getDefault();
public TimeZone getTimeZone() {
return timeZone;
}
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
public List<CampDTO> getListCamp() {
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
UserMB managedBean = (UserMB) sessionMap.get("userMB");
System.out.println("test use==" + managedBean.getUser().getId());
System.err.println("Session"+getUserMB().getUser().getId());
if (listCamp == null) {
listCamp = new ArrayList<CampDTO>();
}
listCamp = ConvertUtils.convertCampToDTO(campEJB.findAll());
return listCamp;
}
public void setListCamp(List<CampDTO> listCamp) {
this.listCamp = listCamp;
}
public User getUser() {
if (user == null) {
user = new User();
}
return user;
}
public void setUser(User user) {
this.user = user;
}
}
I am trying different techniques getting from search but no one works for me?
Is there any configuration for it or how to set/get session bean properly.

Spring inject bean into startup class during server start up

My bean is :
#Component
public class KidsServerStartUp implements ServletContextListener
{
UploadService uplService;
#Autowired
public void setUplService( UploadService uplService )
{
this.uplService = uplService;
}
public void contextInitialized(ServletContextEvent event) {
System.out.println ( uplService );
}
}
In web.xml; I am firstly calling spring framework to set all beans ; then setting the startup listener :
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.kids.util.KidsServerStartUp</listener-class>
</listener>
uplService is getting printed as null !
I think what you are looking for is something like this post.
Since you are using a ServletContextListener spring context will not be used for the creation of the Listener class. But we can get access to the ApplicationContext using the ServletContext.
public class KidsServerStartUp implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
UploadService uplService = springContext.getBean(UploadService.class);
System.out.println ( uplService );
}
}

Resources