0
点赞
收藏
分享

微信扫一扫

Spring 注解驱动——组件注册的其他几种方式

Star英 2022-03-22 阅读 71
spring

一、@ComponentScan 自动扫描组件

1、首先创建 BookController、BookService 以及 BookDao

package org.example.controller;

import org.springframework.stereotype.Controller;

@Controller
public class BookController {
}

package org.example.service;

import org.springframework.stereotype.Service;

@Service
public class BookService {
}

package org.example.dao;

import org.springframework.stereotype.Repository;

@Repository
public class BookDao {
}

2、在配置类上添加 @ComponentScan 注解,并指明需要扫描的包

package org.example.config;

import org.example.pojo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("org.example")
public class MainConfig {

    @Bean
    public Person person(){
        return new Person("lis", "25");
    }
}

3.测试方法

@Test
public void testComponentScan(){
    ApplicationContext ac = new AnnotationConfigApplicationContext(MainConfig.class);
    String[] names = ac.getBeanDefinitionNames();
    for (String name : names) {
        System.out.println(name);
    }
}

4、测试结果
在这里插入图片描述

总结

  • @ComponentScan 注解用于类或接口上,主要指定扫描路径,Spring会把指定路径下带有指定注解的类自动装配到bean容器里。会被自动装配的注解包括@Controller、@Service、@Component、@Repository等等。
  • @ComponentScan 注解需要与 @Configuration 注解搭配使用。其作用等同于 xml 配置文件中的<context:component-scan base-package="com.maple.learn" />配置。
  • @ComponentScan 如果未指定扫描的路径,则默认的扫描路径为该注解类所在的包
举报

相关推荐

0 条评论