preface

Beans in Spring default to the singleton pattern, where a Bean injected throughout the code is the same instance; We call the request-visible scope of the Bean object created in Spring IoC the scope. The @scope annotation can be used to change the Scope of a Bean.

The source code

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
    @AliasFor("scopeName")
    String value(a) default "";

    @AliasFor("value")
    String scopeName(a) default "";

    ScopedProxyMode proxyMode(a) default ScopedProxyMode.DEFAULT;
}
Copy the code

Passing a Scope type directly into a string, such as @scope (“prototype”), is not easy to spot; Spring provides default arguments: ConfigurableBeanFactory.SCOPE_PROTOTYPE, ConfigurableBeanFactory.SCOPE_SINGLETON, WebApplicationContext.SCOPE_REQUEST, WebApplicationContext. SCOPE_SESSION proxyMode also provides parameters: ScopedProxyMode. INTERFACES, ScopedProxyMode. TARGET_CLASS

use

Web scopes (Request, Session, Globalssion). Since the default is singleton mode, prototype is used when annotations are required

@Bean
@Scope("prototype")  // @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MyBean myBean(a) {
    return new MyBean();
}
Copy the code

Each time a Bean is fetched through the container’s getBean method, a new instance of the Bean is generated.

added

Common use mistakes, singleton call more than one example:

@Component
public class SingletonBean {
    @Autowired
    private PrototypeBean bean;
    
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    
}
Copy the code

In the above code, the outer SingletonBean defaults to singleton mode and the inner PrototypeBean is set to prototype mode. It’s not like we’re going to return a new instance every time we create it. Because @AutoWired is injected only once when the singleton SingletonBean is initialized, the PrototypeBean is not created again when the SingletonBean is called (created at injection time, whereas injected only once). Solution 1: Instead of using @autoWired, call the Bean directly each time multiple instances are called; Solution 2: Spring’s solution: Set proxyMode and instantiate it on every request.

The difference between two kinds of proxy mode: ScopedProxyMode INTERFACES: create a JDK proxy mode ScopedProxyMode. TARGET_CLASS: agency model based on class The former can only be the injection of an interface, which can be injected into class.