Spring data MongoDb cannot convert proxy bean - spring

I'm using Spring AOP with AspectJ and Spring Data MongoDb and am having a world of trouble persisting objects.
In this case, I have an AclEntryDaoImpl that exposes AclEntryImpl. When AclEntryImpl is provided a Principal that is a standard Java object (a "non-Spring" bean), mongoTemplate.save() works as expected. However when Principal is a Spring bean, Mongo is unable to convert the object and results in a MappingException org.springframework.data.mapping.model.MappingException: No id property found on class class com.sun.proxy.$Proxy33. All my objects need to be Spring beans so that (a) I keep my objects decoupled and (b) my AOP (LoggingAspect) is invoked.
Lastly, I cannot take advantage of Spring converters because Mongo sees the target object AclEntryImpl as a proxy com.sun.proxy.$Proxy33 and so Converter<Principal, DBObject> is never invoked.
Any and all help would be greatly appreciated!
Snippets:
Here's my Spring XML configuration:
<beans>
<context:component-scan base-package="a.b" />
<context:property-placeholder location="config.properties" />
<aop:aspectj-autoproxy />
<bean id="loggingAspect" class="a.b.LoggingAspect" />
<mongo:db-factory host="${database.host}" port="${database.port}" dbname="${database.dbname}" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="aclEntryDao" class="a.b.AclEntryDaoImpl">
<lookup-method name="createAclEntry" bean="aclEntry" />
</bean>
</beans>
AclEntryImpl:
#Document
#Component
#Scope("prototype")
public class AclEntryImpl implements AclEntry {
#Id
private String id;
private String service;
#DBRef #Expose
private Principal principal;
#Expose
private boolean accessGranted;
#Expose
private List<Permission> permissions;
#Override #Loggable #MongoSaveReturned
public AclEntry save() {
return this;
}
...getters and setters...
}
AclEntryDaoImpl:
#Repository
public abstract class AclEntryDaoImpl implements AclEntryDao {
#Override #Loggable
public AclEntry addEntry(String serviceName, Principal principal, Permission[] permissions, boolean accessGranted) throws Exception {
AclEntry entry = createAclEntry(); //<-- Spring lookup-method
entry.setService(serviceName);
entry.setPrincipal(principal); //<-- com.sun.proxy.$Proxy33
entry.setAccessGranted(accessGranted);
for (Permission permission : permissions) {
if (!entry.addPermission(permission)) {
return null;
}
}
return entry.save();
}
... other DAO methods ...
}
LoggingAspect:
#Aspect
public class LoggingAspect {
#Autowired
private MongoTemplate mongoTemplate;
#Pointcut("execution(!void a.b..*.*(..))")
public void returningMethods() {}
#AfterReturning(pointcut="returningMethods() && #annotation(MongoSaveReturned)", returning="retVal")
public Object mongoSaveReturnedAdvice(Object retVal) {
Logger logger = null;
try {
logger = getLogger(retVal);
mongoTemplate.save(retVal); //<-- throws MappingException
log(logger, "save: " + retVal.toString());
} catch (Exception e) {
log(logger, "throw: " + e.toString());
}
return retVal;
}
... other logging methods ...
}

Related

How to create multiple instances of RestController in Spring boot application?

I want to create different instances of Spring RestController with different instances of beans (service, dao, cache) injected.
Currently, we have implemented this with JAX-RS Restful API.
But when I try to implement the same in Spring RestController, I'm getting below error when Spring tries to create a new bean "product2RestController".
Because bean "product1RestController" is already mapped to the rest url and created.
Stacktrace:
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'product2RestController' method
#Path("/products")
public class ProductLookupRestService {
#Context
HttpServletRequest httpServletRequest;
#Context
HttpServletResponse httpServletResponse;
#Context
UriInfo uriInfo;
private Map<Integer, AbstractProductRestService> productServiceLoopup;
public void setProductServiceLoopup(Map<Integer, AbstractProductRestService> productServiceLoopup) {
this.productServiceLoopup = productServiceLoopup;
}
#Path("/{productId}")
public AbstractProductRestService getReport(#PathParam("productId") int productId) {
AbstractProductRestService productRestService = this.productServiceLoopup.get(productId);
productRestService.setHttpServletRequest(httpServletRequest);
productRestService.setHttpServletResponse(httpServletResponse);
productRestService.setUriInfo(uriInfo);
return productRestService;
}
}
public abstract class AbstractProductRestService {
#Context
protected HttpServletRequest httpServletRequest;
#Context
protected HttpServletResponse httpServletResponse;
#Context
protected UriInfo uriInfo;
protected IProductService productService;
protected IProductCache productCache;
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}
public void setUriInfo(UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
public void setProductService(IProductService productService) {
this.productService = productService;
}
public void setProductCache(IProductCache productCache) {
this.productCache = productCache;
}
#POST
#Path("/filters")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createFilters(Form filterForm) {
//Save the filters and return uuid
ResponseBuilder responseBuilder = Response.created(uriInfo.getAbsolutePathBuilder().path("uuid").build());
return responseBuilder.build();
}
}
public class ProductRestService extends AbstractProductRestService {
#GET
#Path("/filters/{uuid}/detail")
public String getProductDetail(){
// do cache check : productCache
return this.productService.readProductDetail();
}
}
public class ProductServiceImpl implements IProductService{
#Override
public String readProductDetail() {
// Call to dao to get the data
return null;
}
}
<bean id="product1RestService" class="com.poc.jaxrs.rest.ProductRestService">
<property name="productService" ref="product1Service"/>
<property name="productCache" ref="product1Cache"/>
</bean>
<bean id="product2RestService" class="com.poc.jaxrs.rest.ProductRestService">
<property name="productService" ref="product2Service"/>
<property name="productCache" ref="product2Cache"/>
</bean>
<bean id="restProductLookupService" class="com.poc.jaxrs.rest.ProductLookupRestService">
<property name="productServiceLoopup">
<map key-type="java.lang.Integer">
<entry key="1"><ref bean="product1RestService"/></entry>
<entry key="2"><ref bean="product2RestService"/></entry>
</map>
</property>
</bean>
I use below like urls to invoke service.
POST Call: http://localhost:8080/productservice/products/1/filters
GET Call: http://localhost:8080/productservice/products/1/filters/uuid/detail
In my spring application context xml, I'm creating multiple instances of ProductRestService class with different beans (service, cache) instances injected.
Same way I want to create multiple instances of Spring RestController, But I'm getting Ambiguous mapping error.
Thanks for your help in advance.

#Autowired Spring service is null in Play Framework 2.6 application

I'm refactoring an application from Play Framework 2.2.x to Play Framework 2.6.x, and in the updated version of the app an #Autowired spring service is null (I didn't use "new" so that Spring would be confused).
AuthentecatedAction class:
#Scope("prototype")
#Component
public class AuthenticatedAction extends Action<Authenticated>
{
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
ABCUserService ABCUserService;
#Autowired
AccessTokenService accessTokenService;
#Autowired
AccessTokenValidator accessTokenValidator;
#Override
public CompletionStage<Result> call(Http.Context ctx)
{
AccessToken accessToken;
try {
accessToken = accessTokenService.getAccessTokenFromHeader(ctx._requestHeader().headers());
} catch (Throwable throwable) {
return ResultUtils.handleError(new ValidationException(FORBIDDEN, String.format("Access token service is null. %s", throwable.getMessage())));
}
// Some more code here
}
// Some more code here
}
Here accessTokenService is #Autowired, but it is always null.
AccessTokenService class:
#Service
public class AccessTokenService extends JedisBaseService
{
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private ConfigurationService configurationService;
#Autowired
private EncryptionService encryptionService;
#Inject
public AccessTokenService(JedisPool jedisPool) {
super(jedisPool);
}
// some methods
}
JedisBaseService class:
public class JedisBaseService extends Controller
{
private final Logger log = LoggerFactory.getLogger(getClass());
private JedisPool jedisPool;
#Inject
public JedisBaseService(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
// some methods
// TODO: Check that solution with iserting JedisPool works
// See https://github.com/playframework/play-plugins/tree/master/redis for reference
protected Jedis getJedis()
{
return jedisPool.getResource();
}
}
Please, help me understand why #Autowired in AuthentecatedAction class accessTokenService is always null.
EDIT:
I should probably add, that my build.sbt file contains the line:
// https://mvnrepository.com/artifact/org.springframework/spring-context
"org.springframework" % "spring-context" % "4.3.10.RELEASE"
My routes file contains following lines:
POST /accesstokens #api.controller.accesstoken.AccessTokenController.createAccessToken()
DELETE /accesstokens #api.controller.accesstoken.AccessTokenController.deleteAccessToken()
So, I use dynamic controller dispatching to manage controller instances (by prefixing a controller class name with the # symbol in the routes file).
There is a controller for access tokens:
#Controller
public class AccessTokenController extends ABCController
{
#Autowired
private AccessTokenService accessTokenService;
#Autowired
private ABCUserService ABCUserService;
#Autowired
private ActivityCreationService activityCreationService;
#Autowired
private LiveUpdateService liveUpdateService;
#BodyParser.Of(BodyParser.TolerantJson.class)
#ResponseContentType(type = "accessToken")
public Result createAccessToken() throws ABCControllerException
{
// Implementation
}
public Result deleteAccessToken() throws ABCControllerException
{
// Implementation
}
}
Global object of my application that delegates controller instances management:
public class ABCGlobal
{
private final Logger log = LoggerFactory.getLogger(getClass());
protected static ApplicationContext ctx;
private final ActorSystem system;
#Inject
public ABCGlobal(ActorSystem system) {
this.system = system;
}
public static ApplicationContext getApplicationContext()
{
return ctx;
}
public void onStart(Application app)
{
String springConfigurationName = app.configuration().getString("spring.context");
ctx = new ClassPathXmlApplicationContext(springConfigurationName);
log.info("Loading spring configuration: {}", springConfigurationName);
// Some other code
}
// see: http://typesafe.com/blog/announcing-play-framework-21-the-high-velocit
public <A> A getControllerInstance(Class<A> clazz)
{
return ctx.getBean(clazz);
}
// Some other code
}
Here is the associated conf/components.xml file that is used to configure Spring:
<?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-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="api, service"/>
<context:property-placeholder location="classpath:application-base.conf" />
<context:property-placeholder location="classpath:application.conf" />
<bean class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean" id="resourceConverterFactory">
<property name="serviceLocatorInterface" value="service.resource.conversion.ResourceConverterFactory">
</property>
</bean>
<bean class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean" id="scraperFactory">
<property name="serviceLocatorInterface" value="service.scraping.ScraperFactory">
</property>
</bean>
<bean id="storageService" class="service.storage.impl.MongoGridFSStorageService"/>
<bean id="configurationService" class="service.configuration.impl.PlayConfigurationService">
<constructor-arg value="com.typesafe.config.Config" name="config">
</constructor-arg>
</bean>
<bean id="mailService" class="service.mail.impl.MailGunApiMailService"/>
</beans>
And in my application-base.conf file I have the following:
# Spring configuration
# ~~~~~
# Define what spring context should be used.
spring.context="components.xml"

Why my DAO classes are not scanned?

I've been stuck for a week with this problem and there is no way to find a solution in my project using Spring tool suite.
My dispatcher scan packages and creates beans for the controller and service layer but it seems it can't reach the model layer.
This is my servlet-context.xml:
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- <beans:property name="dataSource" ref="dataSource"/> -->
<beans:property name="configLocation" value="classpath:hibernate-annotation.cfg.xml" />
</beans:bean>
<tx:annotation-driven/>
<!-- <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean> -->
I have commented the transactionManager bean because it throws an expection.
The problem comes up when in my UserServiceImpl set UserDaoI as #Autowired
#Service
public class UserServiceImpl implements UserServiceI{
private static final Logger logger =
Logger.getLogger(UserServiceImpl.class);
#Autowired
UserDaoI userDao;
public boolean isRegisteredUser(User user){
logger.debug("Entrando en isRegisteredUser" + logger.getClass());
boolean isRegistered = false;
UserDao uDao = userDao.getUserByDni(user.getDni());
if(!(uDao.getEmail().equals(user.getEmail()))){
isRegistered = true;
}
return isRegistered;
}
I am clueless and desperate.
EDIT:
This is my UserDaoI class, but I think is not relevant.
public interface UserDaoI {
void addUser(UserDao userDao);
UserDao getUser(int id);
boolean updateUser(UserDao userDao);
boolean deleteUser(int id);
List<UserDao> getAllUsers();
UserDao getUserByDni(String dni);
}
This is my UserDaoImpl.java, the source of the problems.
#Repository
public class UserDaoImpl implements UserDaoI{
private static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
#Autowired
SessionFactory sessionFactory;
Session session;
#Override
public void addUser(UserDao userDao) {
session = sessionFactory.openSession();
session.beginTransaction();
session.save(userDao);
session.getTransaction().commit();
session.close();
}
#Override
public UserDao getUser(int id) {
//sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
UserDao userDao = (UserDao) session.get(UserDao.class, id);
session.getTransaction().commit();
session.close();
return userDao;
}
#Override
public boolean updateUser(UserDao userDao) {
assert(userDao!=null);
//sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
session.update(userDao);
session.getTransaction().commit();
session.close();
return false;
}
#Override
public boolean deleteUser(int id) {
//sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
UserDao userDao = new UserDao();
userDao.setId(id);
if(getUser(id)!=null){
try{
session.beginTransaction();
session.delete(userDao);
session.getTransaction().commit();
return true;
}catch(Exception ex){
logger.error("No se ha podido borrar el usuario");
}finally{
session.close();
}
}
return false;
}
#Override
public List<UserDao> getAllUsers() {
//sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
#SuppressWarnings("unchecked")ArrayList<UserDao> userDaoList = (ArrayList<UserDao>) session.createQuery("from user").list();
session.getTransaction().commit();
session.close();
return userDaoList;
}
#Override
public UserDao getUserByDni(String dni) {
session = sessionFactory.getCurrentSession();
session.beginTransaction();
UserDao userDao = (UserDao) session.createQuery("from user where dni = " + dni).uniqueResult();
session.getTransaction().commit();
session.close();
return userDao;
}
}
Why I do not need to autowire my Session?
This is my hibernate config
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/gen</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">fiw48asi</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="com.library.app.dao.user.UserDao"/>
</session-factory>
Now the exception I get is
org.hibernate.hql.internal.ast.QuerySyntaxException: user is not mapped
But it is declared in hibernate-annotation.cfg.xml
Thanks a ton!
The problem is:
'userDaoImpl': Injection of autowired dependencies failed...: Could not autowire field:
because
No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate
In your model, you will need to define a userDaoImpl bean with an #Bean annotation and a Hibernate SessionFactory to allow Spring to create and inject it, e.g.,: add a method to your UserServiceImpl class like this:
UserServiceImpl.java
#Bean
public UserDaoI userDao() {
return new UserDaoImpl();
}
But I notice some mixing of types and models, however, which I think is at the root of your issues, so I'll explain how the service with DAO model works generally with a simpler model.
In a "service and data access object" model, you create a persistence mediator for each entity, conventionally with a DAO suffix and the entity is typically a simple plain ordinary Java object (POJO).
For example, to represent an in-memory user, you might model the entity as follows:
User.java
public class User {
private String name;
// more POJO properties as need..
public void setName(String name) {
this.name = name;
}
public String getName(String name) {
return this.name;
}
// more POJO setters and getters...
}
Now we need a mediator which can create, read, update, and delete these entities from our database. In a DAO pattern, that's the role of the entity's DAO:
UserDao.java
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class UserDao {
#Autowired
private SessionFactory sessionFactory;
public User getUser(long id) {
sessionFactory.getCurrentSession().get(User.class, id);
}
public void addUser(User user) {
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
//...
}
We add a service layer on top of the DAO layer when services either span entities or add some (likely to change) business logic to the entity. For example, supposed we have a registration table which captures registration records in various states for each user:
UserService.java
public class UserService {
#Autowired
private UserDao userDao
#Autowired
private RegistrationDao registrationDao
public boolean isRegistered(long userId) {
// DAOs mediate access to tables
User user = userDao.getUser(userId);
Registration reg = registrationDao.getRegistration();
//
// business logic
//
return isUserRegistered(user, registration);
}
}
With Spring 4, though, I don't hand-code my DAO layers anymore; instead I use Spring Data JPA with the Hibernate JPA provider. Here's a very simple example of how to make this work. You're already using the Hibernate ORM, so you don't "lose" much (quite the opposite, really) by using Spring Data JPA with the Hibernate JPA provider.

Spring autowiring not working, getting `applicationDao` as null

Below are my classes and xml:
#Component
#Service("ApplicationService")
public class ApplicationServiceImpl implements ApplicationService{
public ApplicationDao getApplicationDao() {
return applicationDao;
}
public void setApplicationDao(ApplicationDao applicationDao) {
this.applicationDao = applicationDao;
}
#Autowired
private ApplicationDao applicationDao;
// some methods..
}
#Service
public interface ApplicationService {
// methods...
}
#Component
#Repository("ApplicationDao")
public class ApplicationDaoImpl implements ApplicationDao {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// other methods...
}
public interface ApplicationDao {
// methods...
}
xml file:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven/>
<context:component-scan base-package="com" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<bean id="ApplicationDao" class="com.dao.impl.ApplicationDaoImpl"/>
<bean id="ApplicationService" class="com.service.impl.ApplicationServiceImpl"/>
Here autowiring is not working.in ApplicationServiceImpl, I am getting applicationDao as null. Have not tested sessionFactory in ApplicationDaoImpl.
I know that if I am using #Component then bean declaration in xmnl is not required.
You should not instantiate service like that..
At the time of application loading, spring container will create all instances defined in spring.xml or annotated classes and it's dependencies..
So you have to access them with the following example code..
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
ApplicationService applicationService = (ApplicationService) applicationContext.getBean("ApplicationService");
Since ApplicationService is having property that is ApplicationServiceDAOImpl, it's already been created by spring container and will return you..
But in case of directly instantiating manually by you, you are just creating instance of ApplicationService but not for ApplicationServiceDAOImpl.. so it obviously returns null
I'm currently using this approach only to access beans or services..
update for comment
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
applicationContext = arg0;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
Hope it helps,
try a change like this:
import org.springframework.beans.factory.annotation.Qualifier;
#Autowired
#Qualifier("ApplicationDao")
private ApplicationDao applicationDao;
this give spring a hint.
If you are using annotations in your application, you should denote it using a tag :
<mvc:annotation-driven />
Add this line in application context xml above component scan tag.
Also, if you are using annotations, remove ApplicationDao and ApplicationService bean declarations from xml.
And don't mark you service and dao classes with both #Component and #Service or #Repository annotations. No need to mark them #Component there. Remove it.

spring 2.5.6 DI issue in jsf application

i get NPE(null pointer exception) each time when i try to insert data into database. help me to resolve this issue. i have import all the necessary libraries which are requried for spring.
this is my applicationContext.xml file where i have configure all the beans.
<?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-2.5.xsd">
<bean id="personService" class="com.ecommerce.assignment.service.PersonService">
<property name="personDAO" ref="personDAO" />
</bean>
<bean id="personBean" class="com.ecommerce.assignment.bean.PersonBean" />
<bean id="personDAO" class="com.ecommerce.assignment.dao.PersonDAO" />
</beans>
this is interface of person DAO.
public interface IPersonDAO {
public void addPerson(Person instance);
}
this personDAO class implementing IpersonDAO interface and its unimplemented methods.
public class PersonDAO implements IPersonDAO {
#Override
public void addPerson(Person instance) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction().begin();
session.saveOrUpdate(instance);
session.getTransaction().commit();
session.close();
}
}
this is interface personService.
public interface IPersonService {
public void addPerson(Person instance);
}
public class PersonService implements IPersonService,Serializable {
private IPersonDAO personDAO;
public IPersonDAO getPersonDAO() {
return personDAO;
}
public void setPersonDAO(IPersonDAO personDAO) {
this.personDAO = personDAO;
}
#Override
public void addPerson(Person instance) {
getPersonDAO().addPerson(instance);
}
}
public class PersonBean implements Serializable {
private static final long serialVersionUID = 1L;
private String emailAddress;
private String password;
private String username;
#ManagedProperty(value = "#{personService}")
private IPersonService iPersonService;
public void addPerson(){
try{
Person person = new Person();
person.setUsername(getUsername());
person.setEmailAddress(getEmailAddress());
person.setPassword(getPassword());
iPersonService.addPerson(person);
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
As your person bean is managed by Spring, you should use #Autowired annotation to make dependency injection, or inject it via XML, as you did for PersonService. You can as well declare the bean as #Component and #Scope.
You error is in injecting service in a bean by using JSF's #ManagedProperty annotation that works solely within JSF context, that is, with JSF managed beans, annotated with #ManagedBean, or declared via XML.

Resources