简体   繁体   English

非控制器类的呼叫服务方法

[英]Call service method from non controller class

In HomeController i am doing the following 在HomeController中,我正在执行以下操作

@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 它给了我下面的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?? 如何解决这个问题?

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. 问题是您正在从不受Spring管理的类中调用此函数,因此userDao不在此处注入。

It think that "right" solution is to turn your utility to Spring bean, eg marking it as @Service and call it via Spring. 它认为“正确”的解决方案是将实用程序转换为Spring bean,例如将其标记为@Service并通过Spring调用它。 Alternatively you can retrieve it programmatically using ApplicationContext.getBean() (see here for details) 或者,您可以使用ApplicationContext.getBean()编程方式检索它(有关详细信息,请参见此处

you should declare/annotate your Utility class as a spring bean so that let other bean get injected. 您应该将Utility类声明为/注释为spring bean,以便让其他bean被注入。 in this case, it is EUserService 在这种情况下,它是EUserService

try adding @Component to your Utility class. 尝试将@Component添加到您的Utility类。 I assumed your package is involved by spring annotated bean scanning settings. 我假设您的软件包涉及spring注释的bean扫描设置。

Only Spring managed bean can autowire an instance. 只有Spring托管的bean才能自动装配实例。 Read here 在这里阅读

You annotate Utility with @Component. 您使用@Component注释实用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM