Bean的作用域

说明:Bean存在IOC容器中,默认是单例的(Singleton),可通过@Scope()注解设置为非单例

@Scope(“singleton”):单例,默认设置

(StuMapper类)

/**
 * 标注该层为数据访问层
 */
@Mapper
public interface StuMapper {
}

(MyTest类,使用API的方式获取Bean并打印,看是否为同一个对象)

@SpringBootTest
public class MyTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void printBean(){
        for (int i = 0; i < 100; i++) {
            System.out.println(applicationContext.getBean(StuMapper.class));
        }
    }
}

可以看到,默认获取的Bean对象时同一个,单例的

Bean的作用域_第1张图片


另外,可在给类加@Lazy注解,让Bean对象不在项目启动时就创建完成放在IOC容器中,而是在首次使用时,再创建交给IOC容器管理。

创建一个StuServiceImpl类,启动项目

@Service
public class StuServiceImpl implements StuService {
}

可以看到,项目启动后,IOC容器中StuServiceImpl类的Bean对象就已经创建完成了

Bean的作用域_第2张图片

给StuServiceImp加上@Lazy注解,启动项目,可以看到,容器中目前没有StuServiceImp类的Bean对象

@Service
@Lazy
public class StuServiceImpl implements StuService {
}

Bean的作用域_第3张图片

会在使用@Autowired装配该Bean时再创建

    @Autowired
    private StuService service;

需要注意,使用@Lazy注解延迟创建Bean对象,该Bean对象仍是单例的

@Scope(“prototype”):非单例

将StuMapper类,使用@Scope(“prototype”)注解,设置为非单例

(StuMapper类)

/**
 * 标注该层为数据访问层
 */
@Mapper
@Scope("prototype")
public interface StuMapper {
}

(MyTest类)

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void printBean(){
        for (int i = 0; i < 100; i++) {
            System.out.println(applicationContext.getBean(StuMapper.class));
        }
    }

可以看到,每次获取getBean()都是一个新的Bean对戏那个

Bean的作用域_第4张图片

你可能感兴趣的:(java,jvm,开发语言)