Bean的作用域
1.新建一个ScopeBean类
package com.springboot.chapter3.scope.pojo;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ScopeBean {
}
默认作用域为单例,加上@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)表示多例。
2.测试
package com.springboot.chapter3.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.springboot.chapter3.*")
public class AppConfig {
}
package com.springboot.chapter3;
import com.springboot.chapter3.config.AppConfig;
import com.springboot.chapter3.scope.pojo.ScopeBean;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootTest
class Chapter3ApplicationTests {
@Test
void contextLoads() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
ScopeBean scopeBean1 = ctx.getBean(ScopeBean.class);
ScopeBean scopeBean2 = ctx.getBean(ScopeBean.class);
System.out.println(scopeBean1==scopeBean2);
}
}