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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4289805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:42:39  来源:igfitidea点击:

spring-nullpointerexception- cant access autowired annotated service (or dao) in a no-annotations class

javaspringspring-mvcannotationsautowired

提问by user286806

I have this problem that I cannot fix.

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

From my @Controller, i can easily access my autowired @Serviceclass and play with it no problem. But when I do that from a separate class without annotations, it gives me a NullPointerException.

从我的@Controller, 我可以轻松访问我的自动装配@Service类并使用它没问题。但是当我从一个没有注释的单独的类中这样做时,它给了我一个NullPointerException.

My Controller (works)-

我的控制器(工作)-

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

My separate Java class (not working)-

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

public final class UsersManagementUtil {
  @Autowired
  UserService userService;

or

或者

@Autowired
UserDao userDao;

userService or userDao are always null! Was just trying if any one of them works.

userService 或 userDao 始终为 null!只是在尝试其中任何一个是否有效。

My component scan setting has the root level package set for scanning so that should be OK.

我的组件扫描设置为扫描设置了根级别包,所以应该没问题。

my servlet context -

我的 servlet 上下文 -

<?xml  version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- the application context definition for the
         springapp DispatcherServlet -->
<!-- Enable annotation driven controllers, validation etc... -->

<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="x" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

    <!-- package shortended -->
<bean id="messageSource"
class="o.s.c.s.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages" />
</bean>

<bean  id="dataSource" 
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="username" value="${database.user}" />
    <property name="password" value="${database.password}" />
</bean>

    <!-- package shortened -->
<bean id="viewResolver"
    class="o.s.w.s.v.InternalResourceViewResolver">

    <property name="prefix">
        <value>/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
    <property name="order">
        <value>0</value>
    </property>
</bean>

      <!-- package shortened -->
  <bean id="sessionFactory" 
      class="o.s.o.h3.a.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
    <list>
        <value>orion.core.models.Question</value>
        <value>orion.core.models.User</value>
        <value>orion.core.models.Space</value>
        <value>orion.core.models.UserSkill</value>
        <value>orion.core.models.Question</value>
        <value>orion.core.models.Rating</value>
    </list>
    </property>
        <property name="hibernateProperties">

        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        </props>
        </property>
</bean>

<bean id="hibernateTransactionManager" 
     class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

Any clue?

有什么线索吗?

采纳答案by Jaydeep Patel

From Spring Reference 3.0

Spring 参考 3.0

By default, classes annotated with @Component, @Repository, @Service, @Controller, or a custom annotation that itself is annotated with @Componentare the only detected candidate components.

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

UsersManagementUtilshould be annotated with one of them based on your need.

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

回答by axtavt

Spring dependency injection works only in components managed by Spring. If your UsersManagementUtilis not managed by Spring (i.e. is not a Spring bean), @Autowireddoesn't work inside it. Either declare it as a Spring bean (using <bean>or annotation), or trigger autowiring manually after instantiation of the object using

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

applicationContext.getAutowireCapableBeanFactory().autowireBean(object);