【发布时间】: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