EJB Interview Questions and Answers for freshers
-
What is EJB?
- Answer: Enterprise JavaBeans (EJB) is a server-side component architecture for creating distributed, transactional, and secure applications in Java. It simplifies development by providing a standardized framework for building enterprise-level applications, abstracting away much of the underlying infrastructure complexities.
-
What are the benefits of using EJB?
- Answer: EJB offers benefits such as simplified development (through container management), improved scalability and performance (due to container optimization), enhanced security (using container-managed security), and easier transaction management (through declarative transactions).
-
What are the different types of EJBs?
- Answer: The main types are Session Beans (Stateful, Stateless, Singleton), Message-Driven Beans (MDBs), and Entity Beans (although Entity Beans are largely replaced by JPA).
-
Explain Stateful Session Beans.
- Answer: Stateful Session Beans maintain conversational state across multiple client method invocations. The bean instance is associated with a specific client, and its state persists for the duration of the client's session. This is suitable for applications requiring conversation context.
-
Explain Stateless Session Beans.
- Answer: Stateless Session Beans don't maintain conversational state. Each method invocation is independent; the bean doesn't remember previous interactions. This allows for high scalability and concurrency as multiple clients can access the same bean instance.
-
Explain Singleton Session Beans.
- Answer: Singleton Session Beans have only one instance per JVM. They are useful for tasks requiring shared resources or global application state. Thread safety is crucial in designing Singleton Session Beans.
-
What are Message-Driven Beans (MDBs)?
- Answer: MDBs are asynchronous message consumers. They receive messages from JMS (Java Message Service) queues or topics and process them independently. They're ideal for handling asynchronous tasks and loosely coupled architectures.
-
What is the role of an EJB container?
- Answer: The EJB container is responsible for managing the lifecycle of EJBs, providing services like transaction management, security, persistence, and concurrency control. It handles resource pooling and other infrastructure concerns, abstracting away low-level details from the developer.
-
What is dependency injection in EJB?
- Answer: Dependency Injection is a design pattern where dependencies are provided to an EJB rather than being created within the EJB itself. This promotes loose coupling and testability. EJB containers often support dependency injection through annotations like `@Inject`.
-
Explain the difference between local and remote interfaces in EJB.
- Answer: Local interfaces are used for client-bean interaction within the same JVM, offering better performance. Remote interfaces are used for interactions across JVMs, requiring serialization and network communication, resulting in lower performance.
-
What are EJB transactions?
- Answer: EJB transactions ensure data consistency and integrity. They guarantee that operations either complete entirely or not at all. EJB offers declarative transaction management using annotations like `@TransactionAttribute`.
-
Explain different transaction attributes in EJB.
- Answer: Common transaction attributes include `REQUIRED`, `REQUIRES_NEW`, `MANDATORY`, `NOT_SUPPORTED`, `SUPPORTS`, `NEVER`. Each dictates how the EJB handles transaction contexts.
-
What is JPA and how does it relate to EJB?
- Answer: Java Persistence API (JPA) is a standard for object-relational mapping (ORM). It provides a way to persist Java objects to a relational database. While Entity Beans were previously used for persistence in EJB, JPA is now the preferred approach, often used in conjunction with EJBs.
-
What is the role of the `@PersistenceContext` annotation?
- Answer: `@PersistenceContext` is used to inject a JPA `EntityManager` into an EJB. The `EntityManager` is used to interact with the database.
-
How do you handle security in EJB applications?
- Answer: EJB offers container-managed security, allowing developers to define security roles and permissions. The container handles authentication and authorization, relieving developers from low-level security concerns. Annotations and deployment descriptors are used to configure security.
-
What is a deployment descriptor in EJB?
- Answer: A deployment descriptor is an XML file (ejb-jar.xml) that provides metadata about an EJB application. It specifies details like bean classes, interfaces, transaction attributes, and security settings.
-
Explain the lifecycle of a stateless session bean.
- Answer: A stateless session bean's lifecycle is managed by the container. It's created when needed, and the container can pool instances for performance. It's passivated (its state is stored) when not in use and removed when no longer needed.
-
Explain the lifecycle of a stateful session bean.
- Answer: A stateful session bean's lifecycle is tied to a specific client. It's created when a client invokes a method, its state is maintained during the client's session, and it's passivated (state saved) when inactive. It's removed when the client's session ends.
-
What is the difference between `@PostConstruct` and `@PreDestroy` annotations?
- Answer: `@PostConstruct` is invoked by the container after a bean's initialization. It's used for setup tasks. `@PreDestroy` is called before a bean's destruction; it's used for cleanup.
-
How does EJB handle concurrency?
- Answer: The EJB container manages concurrency, ensuring thread safety. For stateless beans, multiple clients can access the same instance concurrently. For stateful beans, concurrency is handled on a per-client basis. Proper synchronization is crucial for shared resources within a bean.
-
What are some common EJB exceptions?
- Answer: `EJBException`, `CreateException`, `RemoveException`, `FinderException`, `RollbackException`, and others indicating various issues during EJB operations.
-
How do you manage resources in EJB?
- Answer: Resource management is handled through the container. Resources like database connections are pooled and managed, improving efficiency. Developers usually don't need to explicitly manage connection closing; the container takes care of it.
-
What are the advantages of using JNDI in EJB?
- Answer: JNDI (Java Naming and Directory Interface) is used to look up EJBs and other resources. It provides a centralized, standardized way to access components, promoting loose coupling and easier configuration.
-
Explain the concept of interceptors in EJB.
- Answer: Interceptors are a way to add cross-cutting concerns (like logging or security) to EJBs without modifying the bean code directly. They intercept method calls and perform actions before or after the method execution.
-
How can you implement timers in EJB?
- Answer: Timers in EJB allow scheduling tasks to run at specific intervals or times. This is typically done using the `@Schedule` annotation in a timer service.
-
What are the different deployment strategies for EJB applications?
- Answer: Common deployment strategies include using application servers like JBoss, GlassFish, or WebLogic, where EJBs are packaged into JAR files and deployed to the server.
-
How do you handle exceptions in EJBs?
- Answer: Exceptions should be handled using try-catch blocks and appropriate error handling mechanisms. Consider using application-specific exceptions to provide more context.
-
What are some best practices for developing EJB applications?
- Answer: Best practices include following design patterns (like dependency injection), keeping beans loosely coupled, using declarative transactions, and properly managing resources and concurrency. Employing appropriate logging is also important for debugging and monitoring.
-
What is the role of the EJBHome and EJBObject interfaces (in older EJB versions)?
- Answer: In older EJB versions (before EJB 3.0), `EJBHome` represented the factory interface used to create EJB instances, while `EJBObject` provided methods to interact with the bean. These are largely replaced by simpler interfaces in newer versions.
-
How does EJB support distributed transactions?
- Answer: EJB supports distributed transactions using Java Transaction API (JTA) and transaction managers like JTA-compliant application servers. This allows coordinating transactions across multiple resources (databases, message queues).
-
What is CMP (Container Managed Persistence) and BMP (Bean Managed Persistence)?
- Answer: CMP and BMP are older persistence strategies for Entity Beans. CMP allowed the container to manage persistence details, while BMP required developers to handle database interaction directly. JPA largely supersedes these approaches.
-
Explain the concept of pooling in EJB.
- Answer: The EJB container pools instances of stateless session beans to improve performance. This allows efficient reuse of bean instances, reducing the overhead of creating and destroying beans for each request.
-
How can you test EJB components?
- Answer: Testing EJBs often involves using mocking frameworks to simulate dependencies (like databases or other EJBs). Integration testing typically requires deploying the EJB to an application server.
-
What are some common tools used for developing and deploying EJB applications?
- Answer: Common tools include IDEs like Eclipse or IntelliJ IDEA, application servers (JBoss, GlassFish, WebLogic), and build tools like Maven or Gradle.
-
What is the difference between EJB and Spring?
- Answer: Both EJB and Spring are frameworks for building Java enterprise applications. EJB is a more heavyweight, container-managed framework, while Spring is a more lightweight, flexible framework offering similar capabilities but with more control and customization options.
-
What are the limitations of EJB?
- Answer: EJB can be more complex to learn and configure than some alternatives. It's also often considered heavier than other frameworks like Spring. The older versions had steeper learning curves.
-
How do you configure a datasource in an EJB application?
- Answer: Datasource configuration is typically done through the application server's administration console or configuration files. The EJB then accesses the datasource using JNDI lookup.
-
What are some common design patterns used with EJB?
- Answer: Common design patterns include Singleton, Facade, Data Access Object (DAO), and others. The choice of pattern depends on the specific application requirements.
-
Explain how you would design a simple EJB application for managing customer data.
- Answer: A simple design might involve a stateless session bean for business logic (CRUD operations on customer data), a JPA entity to represent customer data, and potentially a DAO to abstract database interactions. The client would interact with the session bean.
-
What is the significance of the `@Stateless` annotation?
- Answer: `@Stateless` annotates a session bean as stateless, indicating that it does not maintain conversational state between method invocations.
-
What is the significance of the `@Stateful` annotation?
- Answer: `@Stateful` annotates a session bean as stateful, indicating that it maintains conversational state across multiple client method invocations.
-
What is the significance of the `@Singleton` annotation?
- Answer: `@Singleton` annotates a session bean as a singleton, ensuring only one instance exists per JVM.
-
What is the significance of the `@MessageDriven` annotation?
- Answer: `@MessageDriven` annotates a bean as a message-driven bean, which asynchronously receives and processes messages from a JMS queue or topic.
-
What is the significance of the `@TransactionAttribute` annotation?
- Answer: `@TransactionAttribute` specifies the transaction behavior for a method in a session bean, such as REQUIRED, REQUIRES_NEW, etc.
-
How would you handle a scenario where a database operation fails within an EJB transaction?
- Answer: The transaction manager will automatically roll back the transaction if an exception occurs, ensuring data consistency. Appropriate exception handling in the EJB would notify the client or log the error.
-
Explain the difference between a local and remote EJB client.
- Answer: A local EJB client runs in the same JVM as the EJB, leading to better performance. A remote client runs in a different JVM and communicates with the EJB through network calls (usually using RMI).
-
What are some alternatives to EJB for building enterprise applications?
- Answer: Spring, Jakarta EE (which is evolving from Java EE), and other frameworks provide alternatives for building enterprise-level applications.
-
What is the role of an EJB deployment descriptor (ejb-jar.xml)?
- Answer: The ejb-jar.xml file contains metadata about the EJB components, such as their interfaces, transaction attributes, and security settings. While annotations are now preferred, the deployment descriptor can still be used for additional configuration.
-
Describe the concept of container-managed relationships in EJB (Entity Beans).
- Answer: In older Entity Beans, container-managed relationships allowed the container to handle the relationships between entities (e.g., one-to-many, many-to-many). JPA now handles this more effectively using annotations.
-
Explain the difference between optimistic and pessimistic locking in EJB (Entity Beans).
- Answer: Optimistic locking assumes that concurrent modifications are rare and checks for conflicts only when committing changes. Pessimistic locking assumes concurrent modifications are frequent and locks records to prevent conflicts.
-
How do you configure a JMS connection factory in an EJB application?
- Answer: A JMS connection factory is typically configured in the application server's configuration files and looked up via JNDI by the EJB.
-
How would you ensure the thread safety of a singleton EJB?
- Answer: Use proper synchronization mechanisms (like `synchronized` blocks or concurrent collections) to protect shared resources within the singleton bean from race conditions.
-
How can you monitor the performance of EJB applications?
- Answer: Use application server monitoring tools to track metrics like transaction times, resource utilization, and error rates. Appropriate logging within the EJBs can also provide valuable performance data.
-
Explain how to handle security roles and permissions in an EJB application.
- Answer: Security roles and permissions are typically defined in the deployment descriptor or through annotations. The EJB container then enforces the security constraints.
Thank you for reading our blog post on 'EJB Interview Questions and Answers for freshers'.We hope you found it informative and useful.Stay tuned for more insightful content!