-1
Logger logger = LoggerFactory.getLogger(CustomWebSecurityExpressionRoot.class);

    @Autowired
    private IUserService userService;

    public CustomWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {
        super(a, fi);
    }

    public boolean isOwner(Integer id) {
        String username = ((UserDetails) getPrincipal()).getUsername();
        User user = new User();
        if (userService == null) {
            logger.debug("USER SERVICE NULL");
        }
        try {
            user = userService.findByUsername(username);
        } catch (NullPointerException e) {
            e.printStackTrace();
            logger.debug("NULL");
        }
        return id == user.getId();
    }

Exception:

java.lang.NullPointerException
    at waterfall.model.User.getId(User.java:62)
    at waterfall.config.CustomWebSecurityExpressionRoot.isOwner(CustomWebSecurityExpressionRoot.java:37)

In other classes, like controller, it works perfectly fine but in the class above userService is null. I have no clue why it is null. What can cause my issue?

THE Waterfall
  • 645
  • 6
  • 17

2 Answers2

0

Autowired only works in spring components like Service, Controller or Component.
You could solve your issue by adding @Component and scanning the given path. However you should look up the consequences of this.

NielsNet
  • 818
  • 8
  • 11
  • After adding `@Component` annotation it threw the following exceptions: `org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.core.Authentication' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}` and `org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customWebSecurityExpressionRoot' defined in file ` – THE Waterfall Sep 17 '18 at 11:32
  • Spring is trying to instanciate the CustomWebSecurityExpressionRoot using the constructor you provided, but can't guess how to create your constructor parameters. – Oreste Viron Sep 17 '18 at 11:59
0

I could find only two possibilities where the autowiring didn't work :

1) Your CustomWebSecurityExpressionRoot hasn't been created by Spring (you instanciated it by yourself ?).

2) Your CustomWebSecurityExpressionRoot is final.

Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
  • Why would `final` would not allow for proper autowiring? Having a `final` service is perfectly valid for Spring and does not impeded with dependency injection. – akortex Sep 17 '18 at 11:23
  • Some classes need to be proxyied by Spring (it is the case for classes with @Transactional annotation for exemple). If the class is not final, Spring can't do so, and the autowiring will fail. – Oreste Viron Sep 17 '18 at 11:57