很多小白包括我自己在学习spring框架的时候都会被眼花缭乱的注解给晕住,所以在这里结合自己的学习及实践来出一期spring注解讲解系列。
这一期我们来讲解@ComponentScan注解,首先我们需要理解在springboot框架中我们似乎很少见到了@ComponentScan注解,这是因为springBoot项目帮我们做了包装并引入自动装配所以"弱化"了@ComponentScan,但是我们深究还是可以看到@ComponentScan的身影这里不做展开。我们仅在spring框架中去讲解@ComponentScan作用毕竟越原始越清晰。
(1)为什么需要@ComponentScan注解
很多同学一开始也奇怪@ComponentScan注解到底有什么作用,为了方便大家理解我会从最基础开始讲解并逐步引入@ComponentScan。
在spring框架中最核心的概念之一是IOC容器,而IOC容器就是帮助我们管理Bean的。@component、@Service、@Controller、@bean等注解是表示标识方法或类成为bean,但是也仅仅是标识即表明可以被spring管理,但是并不能注册到IOC容器中,如果想要注册到IOC容器中还需要其他操作,当前基于注解的方式有两种注册方案。
方案一 手动注册bean到IOC容器
(1)下述我们创建了一个Student类,并加入了@Component这表明Student可以被spring管理了。
package com.hello;
import org.springframework.stereotype.Component;
@Component
public class Student {
}
(2)我们讲当前的Student类注册到IOC容器中,并打印出当前IOC容器中的bean
import com.hello.Student;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
@org.junit.Test
public void test(){
//1.将Student的bean注册到Ioc容器
AnnotationConfigApplicationContext ioc1 = new AnnotationConfigApplicationContext(Student.class);
//2.获取Ioc的Id
String id = ioc1.getId();
System.out.println("IOC的id:"+id);
//3.从IOC容器中获取所有bean的name
String[] beanDefinitionNames = ioc1.getBeanDefinitionNames();
for (String beanName: beanDefinitionNames){
System.out.println(beanName);
}
}
}
下面是打印结果,我们看到了student的名字,这里@component如果不设置nam