Amazon Cyber Monday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

Different Types of Beans in Java Explained

Java beans are ordinary objects used in several different ways, and the word “bean” does not describe just one Java feature. This hands-on guide sorts out JavaBeans, Spring and CDI beans, and the main Enterprise JavaBeans so you can recognize what a project means and choose the right kind for your code.

Ingredients

  • 1 computer with a Java Development Kit (JDK) 17 or later installed; older versions work for the basic JavaBean example.
  • 1 text editor or Java IDE, such as IntelliJ IDEA, Eclipse, or Visual Studio Code.
  • 1 small Java project with a source folder and a main class, so you can try the plain Java example without adding a framework.
  • 1 Spring Boot project, optional, with Spring Context available through the usual project dependencies, for trying a Spring-managed bean.
  • 1 CDI-capable Jakarta EE project, optional, if you want to test CDI or Enterprise JavaBeans examples in a compatible runtime.
  • 1 sample domain concept, such as a recipe, customer, or order, to use consistently while comparing the bean types.
  • About 10 minutes for the plain JavaBean and another 15–30 minutes if you set up framework examples from scratch.

Instructions

  1. Start by separating the meanings. In Java, a bean is generally an object that follows a convention or is managed by a framework or container. Those are related ideas, but they are not interchangeable categories. A class can follow the JavaBeans conventions without Spring or Jakarta EE, while a Spring bean is an object whose creation and lifecycle are managed by Spring. When someone asks for “types of beans,” first check whether they mean object conventions, a particular framework, or older enterprise component types.
  2. Make a plain JavaBean. Create a simple class with private properties, a public no-argument constructor, and public getter and setter methods. For example, a Recipe class might have a private name property and an int servings property, plus getName(), setName(String name), getServings(), and setServings(int servings). A traditional JavaBean usually follows this pattern so tools can discover and manipulate its properties through introspection. It does not need to extend a special base class. Implementing Serializable is sometimes useful for compatibility or serialization, but it is not a universal requirement for every JavaBean.
  3. Use the JavaBean like an ordinary object. Instantiate it with new Recipe(), set its properties, and read them back through the getters. The class remains an ordinary Java object: the Java language itself is not automatically creating a container, injecting dependencies, or choosing a lifecycle. JavaBean conventions are especially familiar in older UI frameworks, libraries that inspect properties, and tools that need predictable getter and setter names. Do not assume that every modern Java class must use setters; immutable classes and records are often better choices when their use case allows it.
  4. Identify a Spring bean. In a Spring application, a Spring bean is an object registered with and managed by the Spring IoC container. A class can be registered through component scanning with an annotation such as @Component, or a configuration class can declare it with @Bean. Spring can then inject that object into other managed objects, commonly through constructor injection. A Spring bean does not have to follow JavaBean getter-and-setter conventions. The default scope is singleton: one shared instance per bean definition in a particular application context, not one magical instance across every process or application. Other scopes, including prototype and web-specific request or session scopes, are available when appropriate.
  5. Try a small Spring example. Mark a service class with @Service (a specialized component annotation), then inject it into a controller or another service through its constructor. Alternatively, define a method annotated with @Bean inside a @Configuration class and return the object from that method. Start the application and let Spring create the context; calling new yourself for a class you expect Spring to inject can bypass container management. Use constructor injection for required dependencies, and avoid changing a shared singleton’s fields to hold per-request user data, since concurrent requests may use the same instance.
  6. Compare CDI beans. CDI, the Contexts and Dependency Injection standard in Jakarta EE, also manages objects, injects dependencies, and provides lifecycle scopes. A CDI bean is discovered and created in a CDI context, with behavior determined by its annotations, scope, and runtime. Common scopes include application, request, and session contexts, though the exact available environment depends on the Jakarta EE setup. CDI and Spring overlap in goals, but their annotations, configuration, extensions, and container behavior are not identical. In a project, follow the framework already in use rather than mixing annotations from different containers without a reason.
  7. Sort the Enterprise JavaBeans by role. EJB is a specific Jakarta EE technology, not a synonym for every object called a bean. The familiar session-bean types are stateless, stateful, and singleton. A stateless session bean does not retain conversational state for one client between method calls; it suits reusable business operations such as calculating a shipping fee. A stateful session bean can retain conversational state for a client across calls, which can fit a multi-step workflow, although web applications often keep such state elsewhere. A singleton session bean represents one shared component instance within its application and can hold shared application-level data, with concurrency concerns handled deliberately. A message-driven bean processes messages asynchronously, commonly from a messaging system, rather than being called like a normal service. EJBs are used in Jakarta EE applications, but many new projects choose lighter Spring or Jakarta CDI components when they do not need EJB services.
  8. Keep entity beans separate from JPA entities. Older Java EE applications may mention entity beans, which were enterprise components for persistent data. They are a legacy approach and are not the same thing as a modern JPA entity. A JPA entity is a class mapped to database data, often annotated with @Entity; it is not automatically a Spring bean or CDI bean just because it is persistent. Modern applications generally use JPA entities with a persistence provider and use separate services or repositories for application behavior. If maintaining older code, check the project’s actual Java EE or Jakarta EE version before changing an entity-bean design.
  9. Label each class in your project by its job. For a quick diagnostic, ask three questions: Does it follow getter/setter property conventions? Does a container create and manage it? Does it implement a specific EJB role? One class may fit more than one description, but the labels answer different questions. For example, a JavaBean-style data object can also be created as a Spring bean, though data-transfer objects usually do not need to be registered with the container. A Spring service is managed by Spring but need not expose JavaBean properties. Naming the framework in a code review—“Spring bean,” “CDI bean,” or “stateless session bean”—prevents confusion.

Tips

  • Use the container already in your application. If a project uses Spring, use Spring’s dependency injection consistently; if it uses CDI, follow CDI conventions. Mixing containers can create confusing lifecycle and injection behavior.
  • Prefer constructor injection for required dependencies. It makes dependencies visible, supports immutable fields, and makes unit tests easier. Use setters when optional reconfiguration or a framework specifically requires them.
  • Do not call every data object a managed bean. A DTO, JPA entity, JavaBean, and Spring bean can overlap, but each term describes a different characteristic. Name the specific role when explaining your design.
  • Watch shared state and scope. A Spring singleton or EJB singleton may serve many requests. Keep request-specific values out of mutable shared fields, or select a suitable scope and concurrency approach.

Serving Suggestions

For a first learning pass, serve the concepts in this order: build the plain JavaBean, run it in a tiny main method, and only then add a container. That progression makes it clear which behavior comes from Java conventions and which behavior comes from Spring, CDI, or an EJB runtime. A small recipe or customer example is enough; a large application can hide the distinction behind configuration and multiple layers.

For a team explanation, pair the class name with its role: “Recipe is a DTO with JavaBean-style accessors,” “RecipeService is a Spring bean,” or “OrderProcessor is a stateless session bean.” This is more useful than saying “it’s a bean,” especially when the application contains several frameworks. In production code, also mention the scope if shared state or request state matters.

Variations

Immutable data-object variation: Replace the mutable JavaBean example with a Java record such as record Recipe(String name, int servings) {} when a compact, immutable data carrier is appropriate. A record is not a traditional JavaBean because it does not provide the standard no-argument constructor and setter pattern, but frameworks can support records in specific roles. Check the framework’s requirements before substituting one.

Spring-only variation: Skip CDI and EJB and build a tiny Spring Boot app with a service and a controller. Annotate the service with @Service, inject it through the controller’s constructor, and inspect the application context only if you need to understand registration. This is usually the most direct route for developers whose project already uses Spring.

Jakarta EE variation: In a Jakarta EE application, compare a CDI-scoped service with an EJB session bean in the runtime your team actually deploys. Focus on required services such as transactions, messaging, security, and concurrency rather than choosing EJB merely because it has a familiar name. Framework versions and server support affect which annotations and APIs are available.

Storage and Reheating

There is no cooked dish to refrigerate here; for this coding recipe, “storage” means keeping a runnable example. Save the source files and build configuration in version control, and add a short README noting the JDK and framework versions. A plain JavaBean example should remain easy to compile for years, but framework examples can become stale as dependencies and Jakarta package names change. Recheck a tutorial project after about 6–12 months, or whenever you upgrade its framework or Java version.

To “reheat” the example, run the project’s test or build command rather than copying old compiled output. For a Maven project, that is commonly mvn test; for Gradle, it is commonly ./gradlew test. Allow a few minutes for dependency downloads on the first run. If the app fails, verify the installed JDK, dependency versions, and whether the correct runtime supports the annotations in use. Do not keep credentials or real customer data in a learning project.

Related

Frequently Asked Questions

Are JavaBeans and Spring beans the same thing?
A JavaBean usually means a class that follows conventions for properties, such as private fields with public getters and setters and commonly a public no-argument constructor. A Spring bean means an object managed by the Spring container. A class can satisfy both descriptions, but neither term automatically implies the other.

What are the main types of EJB?
The commonly discussed EJB types are stateless session beans, stateful session beans, singleton session beans, and message-driven beans. The first three serve business operations with different state and lifecycle behavior; message-driven beans handle messages asynchronously. Entity beans are a legacy technology and should not be confused with JPA entities.

Is a JavaBean required to implement Serializable?
No, not as a universal rule. Serialization has been expected in some older frameworks or particular use cases, but the basic JavaBean conventions do not make it mandatory. Follow the needs of the library or application rather than adding serialization without a reason.

Is a Spring bean always a singleton?
No. Singleton is Spring’s default scope, meaning one instance per bean definition in a given application context. Spring also supports prototype and, in web-aware applications, scopes such as request and session. Choose a scope based on lifecycle needs, and remember that scope alone does not make mutable shared state thread-safe.

Is a JPA entity a bean?
A JPA entity is a persistent domain object managed by a JPA provider. People may casually call it a bean, and it may have JavaBean-style accessors, but it is not automatically a Spring or CDI managed bean. Persistence management and dependency-injection management are separate concerns.

Which bean type should I use in a new Java project?
Choose based on the project’s framework and the job the object must perform. Use a plain class or record for simple data, a Spring or CDI bean for container-managed services and dependency injection, and an EJB type when the Jakarta EE application benefits from its specific services and runtime support. Avoid selecting a category just because it is called a bean.

Different Types of Beans in Java Explained
Scroll to top