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").

    @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.

    @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

expert

I want to know what actually happens when you annotate a method with @Transactional?

senior

What is the default scope in the web context?

middle

Name some of the Design Patterns used in the Spring Framework?

Bình luận

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

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