我已经在我的servlet xml中配置了sessionfactory,并通过SETTER注入将其注入到bean中。我已经在bean的setter方法中添加了一个日志。服务器启动时获取日志。看起来它正在将属性注入我的bean中。但是当我调用该方法时,它将变为null。附上我的代码..
<** Bean configuration Starts **>
<bean id="userServiceImpl" class="com.springapp.oranju.Service.UserServiceImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory"
class="
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>/WEB-INF/config/hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<** Bean configuration ends **>
<** Bean Class starts**>
public class UserServiceImpl implements UserService{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
try {
System.out.println(" **********************************************************************************"+this.sessionFactory.getReference());
} catch (NamingException e) {
e.printStackTrace();
}
}
public void validateLogin(UserVO userVO) {
System.out.println(sessionFactory);
sessionFactory.getCurrentSession().save(new User(new UserVO()));
}
}
<** Bean Class ends**>
<** call from controller starts **>
UserServiceImpl userService = new UserServiceImpl();
userService.validateLogin(new UserVO());
<** call from controller ends **>
I have tried using the @ Autowired.. but it was helpless.
Awaiting for a answer !.........
答案 0 :(得分:1)
您必须在控制器中自动装配UserServiceImpl。如果您通过 new UserServiceImpl()手动实例化它,则Spring IoC容器不知道UserServiceImpl依赖于sessionFactory。
在应用程序上下文xml中包含以下元素:
<context:component-scan base-package="org.example"/>
其中base-package元素是服务类的公共父包,如果您在控制器中使用spring mvc,autowird服务:
@Controller public class ExampleController {
@Autowired private UserServiceImpl userService;
}