我是靠谱客的博主 快乐云朵,最近开发中收集的这篇文章主要介绍Spring - @ComponentScan用法及手写简单实现,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

@ComponentScan:默认扫描与当前类所在包下的带有@Service、@Controller、@Component、@Repository 注解修饰的类装入到Spring容器中。

package com.demo.test;

import org.springframework.stereotype.Controller;

@Controller
public class TestController {
}
package com.demo.test;

import org.springframework.stereotype.Service;

@Service
public class TestService {
}
package com.demo.test;

import org.springframework.stereotype.Repository;

@Repository
public class TestRepository {
}
package com.demo.test;

import org.springframework.stereotype.Component;

@Component
public class TestComponent {
}

首先写了四个组件,分别用了四个不同的注解。

接下来,写@ComponentScan修饰的类。

package com.demo.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;


@ComponentScan(basePackages = {"com.demo.test"},
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})},
        useDefaultFilters = false)
public class TestConfig {
}

basePackages:设定扫描的包。

includeFilters:设定过滤器。

@Filter的type设定过滤注解,本文中classes设定过滤Controller和Service的Class对象

useDefaultFilters:设定false。与includeFilters联合使用,表示只装配classes给出的Class对象标注的类

 

最后再写测试类:

package com.demo.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestDemo2 {

    public static void main(String[] args) {
        // 可以基于配置类创建应用上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }
}

 AnnotationConfigApplicationContext:可以基于配置类创建应用上下文。

getBeanDefinitionNames():获得在spring容器中注册的bean的名字。

 

控制台输出:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
testConfig
testController
testService

 


手写简单实现:

    private List<String> classNames = new ArrayList<>();
    private Map<String, Object> ioc = new HashMap<>();
    private void doScanner(String packageName) {
        URL url = getClass().getClassLoader().getResource(packageName.replaceAll("\.", "/"));
        File dir = new File(Objects.requireNonNull(url).getFile());
        for (File file : Objects.requireNonNull(Objects.requireNonNull(dir).listFiles())) {
            if (file.isDirectory()) {
                doScanner(packageName + "." + file.getName());
            }
            String className = packageName + file.getName().replace(".class", "");
            classNames.add(className);
        }
    }

    private String toLowerCaseOfFirstCharacter(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private void doInstance() {
        for (String className : classNames) {
            try {
                Class<?> cls = Class.forName(className);
                if (cls.isAnnotationPresent(MyController.class)) {
                    ioc.put(toLowerCaseOfFirstCharacter(className), cls.newInstance());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

最后

以上就是快乐云朵为你收集整理的Spring - @ComponentScan用法及手写简单实现的全部内容,希望文章能够帮你解决Spring - @ComponentScan用法及手写简单实现所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部