I have a question regarding declaration of classes in applicationContext.xml
In applicationContext.xml do we need to specify all the classes from the application? E.g. In my small web application I have a Entity class, Service class and DAO class. So currently it is defined as
<!-- Beans Declaration -->
<bean id="Employees"
class="net.test.model.Employees" />
<!-- User Service Declaration -->
<bean id="
EmployeeService" class="net.test.employees.service.EmployeeService">
<property name="employeesDAO" ref="EmployeeDAOImpl" />
</bean>
<!-- User DAO Declaration -->
<bean id="EmployeeDAO" class="net.test.employee.dao.EmployeeDAOImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
So if I have multiple entity, service and dao classes do I need to mention all those classes in applicationContext.xml
?
Any insight into this is highly appreciable.
Regards
Update 1
ManagedBean
@ManagedBean(name="empMB")
@Named
@Scope("request")
public class EmployeesManagedBean implements Serializable {
and I have Inject annotation
@Inject
EmployeesService employeesService;
In EmployeesService I have annotations like
@Named
public class EmployeesService implements IEmployeesService {
@Inject
EmployeesDAO employeesDAO;
@Override
public List<Employees> getEmployees() {
return getEmployeesDAO().getEmployees();
}
and finally in applicationContext.xml I have
<context:component-scan base-package="net.test" />
Now the problem is when I run my application I am getting
java.lang.NullPointerException at
net.test.managed.bean.EmployeesManagedBean.getEmpList(EmployeesManagedBean.java:53)
What am I doing wrongly to get nullpointer exception?
The bean declaration in the application context is to register the bean in the application container.
If the bean is not registered, the container wouldn't be able to dependency inject any instance of that class, or apply interceptors to the object of the class.
So unless the reference of bean is not required for any task like intercepting it or inject it, or create default singleton object of it, there is no need to declare it in the applicationContext.xml
Hope this helps.
No. Declaring model classes like your
net.test.model.Employees
is pointless unless you need a prototype to work with, something like initializing its values, but you can do this directly in the class and just instantiate it.As I explained before, entity classes no. Services and DAOs are ok because most of the time you need DAOs injected to the Services (and that's the point of DI). But of course, if you create 3 DAOs and you want them to be injected in your 3 Services, then mention them in your Spring XML Bean Definition file (what you call
applicationContext.xml
).But one thing, you may want to use package scanning autodetection and annotation based config to avoid writing everything in your Bean Definition File.
Ideally yes, another way can be using Spring Annotations so that you don't to add multiple entries in xml.