Reputation: 27
I have configured the sessionfactory in my servlet xml and injected the same into a bean by SETTER injection. I have put a log in the setter method of bean. Upon server start am getting the log. It seems like it is injecting the property into my bean. but when i call the method, it is coming as null. Attached my code..
<** 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 !.........
Upvotes: 0
Views: 578
Reputation: 3622
you have to autowire UserServiceImpl in controller. If you instantiate it manually by new UserServiceImpl(), spring IoC container has no idea that UserServiceImpl depends on sessionFactory.
include the following element in you application context xml:
<context:component-scan base-package="org.example"/>
where the base-package element is a common parent package for the service classes, and if you are using spring mvc, autowird service in your controller by:
@Controller public class ExampleController {
@Autowired private UserServiceImpl userService;
}
Upvotes: 1