You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

58 lines
2.0 KiB

package cc.bnblogs.beanstudy.bean;
import cc.bnblogs.beanstudy.entity.Bird;
import cc.bnblogs.beanstudy.entity.Fish;
import cc.bnblogs.beanstudy.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.jupiter.api.Assertions.*;
/**
* @description:
* @author: zfp@bnblogs.cc
* @date: 2023/3/28 23:07
*/
@SpringBootTest
public class WebConfigTest {
/**
* 单例模式下:
* 在容器启动之前,先调用对象的无参构造器创建对象,然后调用初始化方法,
* 在容器关闭的时候调用销毁方法
*/
/**
* 多例模式:
* IOC容器启动的时候并不会去创建对象,而是在每次获取的时候才会去调用方法创建对象,
* 创建完对象后再调用初始化方法。但在容器关闭后,Spring并没有调用相应的销毁方法,
* 这是因为在多例模式下,容器不会管理这个组件(只在需要时帮你创建这个组件)
*/
@Test
void testBean() {
// 返回 IOC 容器,使用注解配置,传入配置类
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
User user = context.getBean(User.class);
System.out.println(user);
// 关闭 IOC 容器
context.close();
}
@Test
void testBird() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
System.out.println("容器创建成功");
Bird bird = context.getBean(Bird.class);
context.close();
}
@Test
void testFish() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
System.out.println("容器创建成功");
Fish fish = context.getBean(Fish.class);
context.close();
}
}