To create a managed bean, add the @javax.annotation.ManagedBean
annotation to the Java class. For example:
package com.sample.sales.core; import com.sample.sales.entity.Order; import javax.annotation.ManagedBean; @ManagedBean(OrderWorker.NAME) public class OrderWorker { public static final String NAME = "sales_OrderWorker"; public void calculateTotals(Order order) { } }
It is recommended to assign a unique name to the bean in form of {project_name}_{class_name}
and to define it in the NAME
constant.
The managed bean class should be placed inside the package tree with the root specified in the context:component-scan
element of the spring.xml file. In this case, the spring.xml
file contains the element:
<context:component-scan base-package="com.sample.sales"/>
which means that the search for annotated beans for this application block will be performed starting with the com.sample.sales
package.
To provide an ability to substitute the implementation in the future, it is recommended to give the bean a separate interface:
// OrderWorker.java – interface package com.sample.sales.core; import com.sample.sales.entity.Order; public interface OrderWorker { String NAME = "sales_OrderWorker"; void calculateTotals(Order order); }
// OrderWorkerBean.java – implementation package com.sample.sales.core; import com.sample.sales.entity.Order; import javax.annotation.ManagedBean; @ManagedBean(OrderWorker.NAME) public class OrderWorkerBean implements OrderWorker { @Override public void calculateTotals(Order order) { } }
Managed beans can be created on any tier, because the Spring Framework container is used in all standard blocks of the application.