Spring注解(一) 从XML升级

361 阅读1分钟

注册组件

以前是将组件配置到XML文件中,配置一个对应的person bean组件, 在主类中加载bean到容器中, 再将从容器中取出person对象

配置文件版:

注解版手动加载

升级到注解版:

配置类中, 给容器注册一个Bean

  1. 类型为方法返回值类型
  2. id默认用方法名

@Configuration
public class MainConfig {
  @Bean
  public Person person() {
    return new Person();
  }
}
  • 运行流程
  1. 主类加载配置类,将配置类中的@Bean 注入容器
  2. 主类从容器中拿到Person对象

加入包扫描!

  • 配置类上加上@ComponentScan, 自动把带有下列注解的类加入容器.
    1. @Component
    2. @Repository
    3. @Controller
    4. @Service
  • 主类
 public static void main(String[] args) {
 // 加载带有包扫描的配置类
        AnnotationConfigApplicationContext ioc = new AnnotationConfigApplicationContext(PersonConfig.class);
        // 打印加入ioc容器的组件
        String[] beans = ioc.getBeanDefinitionNames();
        for (String bean : beans) {
            System.out.println(bean);
        }
    }
  • 结果
15:05:18.209 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
15:05:18.211 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
15:05:18.212 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
15:05:18.216 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
15:05:18.223 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'personConfig'
15:05:18.227 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'person'
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
personConfig
person

从结果看 只扫描了类进来, 接口加入注解也没有扫描进来

自动配置(待补充)

springboot中也不用写包扫描了, @SpringBootApplication, 里已经包含了包扫描, 会扫描当前目录下所有文件夹的组件加入容器中.