【问题标题】:Correct usage of spring @Autowired annotationspring@Autowired注解的正确使用
【发布时间】:2017-12-09 07:31:13
【问题描述】:

我正在为 RESTFul API 开发一个 jax-rs 项目

我选择使用 spring 来自动注入我的依赖项

import org.springframework.beans.factory.annotation.Autowired;

@Autowired
private UserManager userManager;

这是我的 spring.xml

<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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config/>

    <!-- Manager -->
    <bean id="userManager" class="com.mypackage.manager.UserManagerImpl"/>
    <bean id="cardManager" class="com.mypackage.manager.CardManagerImpl"/>
    <bean id="albumManager" class="com.mypackage.manager.AlbumManagerImpl"/>

    <!-- Dao -->
    <bean id="userDao" class="com.mypackage.dao.UserDaoImpl"/>
    <bean id="cardDao" class="com.mypackage.dao.CardDaoImpl"/>

    <!-- Session factory for hibernate -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="file:web/WEB-INF/hibernate.cfg.xml"/>
    </bean>

</beans>

但我在这里遇到了 NullPointerException :

userManager.getUserById(1);

这里是方法的代码:

public UserDto getUserById(Integer userId) throws NotFoundException {
    /*User user = userDao.findById(userId);*/
    User user = new User();
    user.setUsername("creekorful");
    user.setAvatarUrl("myavatar/avatar.image");
    user.setEmail("creekorful@gmail.com");
    user.setUserStatus(UserStatus.ACTIVATED);
    user.setAccountType(AccountType.ADMINISTRATOR);
    return new UserDto(user);
}

我是否需要让 spring 自动实例化并注入我的经理?因为无论我尝试使用什么解决方案,我的 userManager 似乎仍然为空。我想我错过了关于 spring 的一些功能......

注意:我已将 spring.xml 放入 .war 中的 WEB-INF/class 目录中

提前致谢

【问题讨论】:

  • 我不会混合注释和基于 XML 的配置。任选其一。
  • 我更喜欢注释。但是注册 bean 不需要 XML 配置吗?
  • 您不需要任何 XML 配置。
  • 那么如何指定注入呢?如何配置弹簧?
  • 最近的任何教程都会向您展示如何进行完整的注释配置。如果你使用Spring Boot很容易,否则你需要配置DispatcherServlet

标签: spring autowired spring-bean


【解决方案1】:

在您的 spring.xml 中,您还需要确保已启用如下注释:

<context:annotation-config/>

希望有帮助!

【讨论】:

  • 谢谢,我已将该行添加到我的 spring.XML 中,但遗憾的是没有任何改变...我错过了什么吗?
  • 在您的 bean 定义中,您将类设置为 UserManagerImpl。不应该只是 UserManager,因为这是您尝试自动装配的字段类型?
  • 我要试试这个。但我认为 bean 应该指向我的用户管理器接口的实现而不是接口
  • 你可以试试(我假设你的意思是你的用户管理界面的实现)。
  • 好的,我想我现在明白了。问题可能出在您的 public static void main 方法中。你在做这样的事情吗? ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");使用自动装配将在您的其他类中,但在您的主要方法中,您希望做一些更像 appContext.getBean("UserManagerImpl");同样,自动装配通常在您的类中,而您将从上下文中获取 bean。
猜你喜欢
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 2014-10-25
  • 2021-10-07
  • 2012-05-01
  • 2016-05-30
  • 2011-04-01
相关资源
最近更新 更多