4.2.4.1. Creating a Bean

To create a managed bean, add the @org.springframework.stereotype.Component annotation to the Java class. For example:

package com.sample.sales.core;

import com.sample.sales.entity.Order;
import org.springframework.stereotype.Component;

@Component(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 the {project_name}_{class_name} form and to define it in the NAME constant.

Tip

The @javax.annotation.ManagedBean can also be used for the managed bean definition, but it can cause problems when deploying the application into some application servers. Therefore we recommend to use only @Component annotation from Spring Framework.

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.

Managed beans can be created on any tier, because the Spring Framework container is used in all standard blocks of the application.