-1

In HomeController i am doing the following

@Controller
public class HomeController {

    @Autowired
    private EUserService userDao;

    @RequestMapping(value = "/")
    public String setupForm(Map<String, Object> map) {
       User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       EUser currentUser = userDao.findUserByName(user.getUsername());
           System.out.println(currentUser.getUserName());
        }
}

It works fine and shows me the output properly. Now If I do the same thing in a non controller type class like following

public class Utility {
    @Autowired
    private EUserService userDao;

    public void getLoggedUser() {
        User user = (User) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        EUser currentUser = (EUser) userService.findUserByName(user
                .getUsername());
        System.out.println(currentUser.getUserName());

    }
}

it gives me the following NullPointerException

SEVERE: Servlet.service() for servlet [spring] in context with path [/Ebajar] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException

How to fix this??

LynAs
  • 6,407
  • 14
  • 48
  • 83

3 Answers3

2

The problem is not that you are calling this not from controller. The problem is that your are calling this from class that is not managed by Spring, so the userDao is not injected here.

It think that "right" solution is to turn your utility to Spring bean, e.g. marking it as @Service and call it via Spring. Alternatively you can retrieve it programmatically using ApplicationContext.getBean() (see here for details)

Community
  • 1
  • 1
AlexR
  • 114,158
  • 16
  • 130
  • 208
1

you should declare/annotate your Utility class as a spring bean so that let other bean get injected. in this case, it is EUserService

try adding @Component to your Utility class. I assumed your package is involved by spring annotated bean scanning settings.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • "I assumed your package is involved by spring annotated bean scanning settings." what does this means? – LynAs Feb 17 '14 at 10:24
  • 1
    @LynAs it means, your package should be included in spring's annotated bean scanning config. If you add `@Component` or `@Service` – Kent Feb 17 '14 at 10:35
1

Only Spring managed bean can autowire an instance. Read here

You annotate Utility with @Component.

titogeo
  • 2,156
  • 2
  • 24
  • 41