0

I am new to this Spring and trying to learn it.

I am using basic auth jersey and using spring to inject my db props and instantiate the class. However I am getting null pointer exception when I try this with a REST call using postman.

Below is code snippet

AppContx.xml

<context:annotation-config />

<context:component-scan base-package="com.rest" />


<bean id="userDao" class="com.rest.dao.UserDao">
    <property name="dataSource" ref="ds" />
</bean>

<bean id="ds" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/Weber" />
    <property name="resourceRef" value="true" />
</bean>

Filter

  @Provider
  public class AuthenticationFilter implements ContainerRequestFilter {

/*ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IuserDao userDao = (IuserDao) ctx.getBean("userDao");*/

@Autowired 
UserDao userDao;

public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}

public UserDao getUserDao() {
    return userDao;
}
  if (userDao.getUSerForAuthentication(password, username) == 1) {
            String userRole = "ADMIN";
            if (rolesSet.contains(userRole)) {
                isAllowed = true;
            }

DAO

@Autowired 
private DataSource dataSource;


public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

I am successfully able to inject DB properties to my data source using @Autowired but I am unable to instantiate the UserDao in my Filter class.

Thank You

Mark

mark
  • 47
  • 9
  • I suggest, remove this from your code. and add @Component to your UserDao class – Umesh Kumar Sharma Mar 15 '18 at 04:57
  • Why you required getter & setter for userDao ? Can you please remove it and try again. – Vinit Solanki Mar 15 '18 at 05:00
  • Hi Vinit yeah true we dont need them. But my conern was I am unable to create a new object of UserDao in my Filter class. Also removed getter and setter methods no luck. still I am getting NPE – mark Mar 15 '18 at 05:05
  • I ran into this same issue when attempting to Autowire into a filter and into a HandlerInterceptor. See this article: https://stackoverflow.com/questions/3645650/using-some-beans-in-filter-bean-class. I implemented something similar and it works. – neal Mar 16 '18 at 04:49

0 Answers0