简介
Spring IoC 容器是一个管理 Bean 的容器,在 Spring 的 定义中,它要求所有的 IoC 容器都需要实现接口 BeanFactory ,它是一个顶级容器接口 。
在现实中使用的大部分 Spring IoC 容器是 ApplicationContext 接口的实现类。
在 Spring Boot 当中主要是通过注解来装配 Bean 到 Spring IoC 容器中,AnnotationConfigApplicationContext
就是一个基于注解的 IoC 容器。
使用@Bean注解装配Bean
Java对象。
@Setter
@Getter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String userName;
}
配置类。
import com.demo.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(name = "user")
public User user(){
return new User();
}
}
测试类。
@Test
public void test(){
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(AppConfig.class);
User bean = applicationContext.getBean(User.class);
System.out.println(bean);
}
使用包扫描@ComponentScan装配Bean
在配置类上添加@ComponentScan指定包扫描的范围。
@Configuration
@ComponentScan(basePackages = "com.demo.entity")
public class AppConfig {
}
在实体类上添加@Component注解表示需要装配到IOC容器。
@Component
public class User {
private String userName;
}