Câu hỏi phỏng vấn Spring
Câu hỏi

How do you define a bean scope?

Câu trả lời

To define a bean scope in Spring, you specify the lifecycle and visibility of a bean within the application contexts it is used. The Spring framework supports several scopes, but the most commonly used are singleton and prototype. Additionally, there are web-aware scopes like request, session, application, and websocket.

Here's how you can define a bean scope:

  1. Annotation-based Configuration: You can use the @Scope annotation on the bean definition to specify its scope. For example, to define a singleton scope (which is the default), you can use @Scope("singleton") or simply omit the scope as singleton is the default. For a prototype scope, you would use @Scope("prototype").

    java Copy
    @Component
    @Scope("prototype")
    public class MyPrototypeBean {
        // class body
    }
  2. Java-based Configuration: When using Java configuration, you can use the @Bean annotation along with @Scope in a configuration class.

    java Copy
    @Configuration
    public class AppConfig {
        @Bean
        @Scope("singleton") // This is optional as singleton is the default scope
        public MySingletonBean mySingletonBean() {
            return new MySingletonBean();
        }
    
        @Bean
        @Scope("prototype")
        public MyPrototypeBean myPrototypeBean() {
            return new MyPrototypeBean();
        }
    }
  3. XML-based Configuration: In XML conf...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is Join point?

junior

How to integrate Java Server Faces (JSF) with Spring?

senior

What are the different types of Advices?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào