spring注解驱动开发-组件注册-@ComponentScan自动扫描&指定扫描组件

1.@ComponentScan使用

1.新建一个类ConfigComponentScan,类上加@ComponentScan(value ="springanntition.configbean");表明要扫描springanntition.configbean包下的类


@Configuration
@ComponentScan(value ="springanntition.configbean")
public class ConfigComponentScan {
    // @Bean含义:给容器中注册一个Bean;类型为返回值类型,id默认是用方法名作为id,也可以起别名称
    @Bean
    public Person personDy() {
        return new Person("ddf", 25);
    }
}

就相当于扫描此路径下,然后test包下再建立同路径名下的测试类,pom.xml要添加junit包哦

添加测试类MainTestComponentScan如下

package springannotion.configbean;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import springanntition.configbean.ConfigComponentScan;


public class MainTestComponentScan {
    @Test
    public void getIOCBean(){
        // 需要写上你需要的配置类哦!
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigComponentScan.class);
        // 获取bean的名字
        String[] beannames = context.getBeanDefinitionNames();
        for (String name : beannames) {
            System.out.println(name);
        }
    }
}

咱们运行一下,除了默认的容器外,标红的就是我们获取到的,configComponentScan是配置类本身的名字,mainConfig是上一篇讲解建立的配置类,以及@Bean的配置全部都获取到了。

我们再建立一个controller类和service类来测试@ComponentScan数组的方式

package anntiontest;

import org.springframework.stereotype.Controller;

@Controller
public class TeseController {
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值