一句话,@Component实现的就是bean的注入,实例化到spring容器里,相当于SSM配置文件中的<bean class = >。
打开idea,我们可以看到,常见的诸如@Controller,@Service,@Repository三个注解,里面的申明都加入了@Component注解
和@Component注解配套的,就是@ComponentScan,我们光标记了不行,还需要一个东西来扫描我们加上@Component注解的类,我们要让spring知道哪些类,是需要以bean的形式注入到spring容器里。
常见用法就是在类上直接加上@ComponentScan,后面的参数就是我们要扫描的包名
@ComponentScan(basePackages = "com.example.demo.configuration")
下面举一个简单的例子:
我们新建一个bean对象,加上@Component注解
@Component
public class TestBean {
private String username;
private String url;
private String password;
public void sayHello() {
System.out.println("TestBean sayHello...");
}
public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}
public void start() {
System.out.println("TestBean 初始化。。。");
}
public void cleanUp() {
System.out.println("TestBean 销毁。。。");
}
}
然后我们在项目自带的测试类里面去测试一下
(1)当我不加@ComponentScan的时候代码
public class ConfigurationTest {
public ConfigurationTest() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationTest.class);
TestBean testBean = context.getBean(TestBean.class);
testBean.sayHello();
}
}
运行后可以看到控制台报错了,因为我们没有加扫描,spring找不到这个bean对象
16:10:40.250 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'configurationTest'
TestConfiguration容器启动初始化。。。
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.configuration.TestBean' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1177)
at com.example.demo.configuration.ConfigurationTest.main(ConfigurationTest.java:18)
Process finished with exit code 1
(2)加上@ComponentScan的时候代码
@ComponentScan(basePackages = "com.example.demo.configuration")
public class ConfigurationTest {
public ConfigurationTest() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationTest.class);
TestBean testBean = context.getBean(TestBean.class);
testBean.sayHello();
}
}
运行看看呢
16:14:03.290 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'configurationTest'
TestConfiguration容器启动初始化。。。
16:14:03.296 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'testBean'
TestBean sayHello...
Process finished with exit code 0
这时候我们可以看到,正常注入bean,并且方法调用正常