spring-nullpointerexception-无法在无注释类中访问自动连接的带注释的服务(或dao)

我有这个问题,我无法解决。

从我的@Controller ,我可以轻松访问我的自动assembly的@Service类并使用它没有问题。 但是当我从没有注释的单独类中执行此操作时,它会给我一个NullPointerException

我的控制器(工程) –

 @Controller public class UserController { @Autowired UserService userService;... 

我的单独Java类(不工作) –

 public final class UsersManagementUtil { @Autowired UserService userService; 

要么

 @Autowired UserDao userDao; 

userService或userDao始终为null! 只是尝试其中任何一个工作。

我的组件扫描设置具有用于扫描的根级别包,因此应该没问题。

我的servlet上下文 –

                     /   .jsp   0        orion.core.models.Question orion.core.models.User orion.core.models.Space orion.core.models.UserSkill orion.core.models.Question orion.core.models.Rating     ${hibernate.dialect} ${hibernate.show_sql} ${hibernate.hbm2ddl.auto}       

任何线索?

来自Spring Reference 3.0

默认情况下,使用@Component@Repository@Service @Controller@Repository注释的@Component或自身使用@Component注释的自定义注释是唯一检测到的候选组件。

UsersManagementUtil应根据您的需要使用其中一个进行注释。

Springdependency injection仅适用于Spring管理的组件。 如果您的UsersManagementUtil不是由Spring管理的(即不是Spring bean),则@Autowired在其中不起作用。 要么将它声明为Spring bean(使用或注释),要么在使用对象实例化后手动触发自动assembly

 applicationContext.getAutowireCapableBeanFactory().autowireBean(object);