ComponentScan注解

1、配置类
package com.configuration;

import com.bean.Person;
import com.tools.service.Service001;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;


/**
* @auto dh
* @create 2020-04-25-11:04
*/
@Configuration
//ComponentScan(basePackages={"指定的包"}) 扫描指定包下带注解的文件 //excludeFilters 排除要扫描的文件
@ComponentScan(basePackages={"com.tools"},excludeFilters = {
                  // 排除要扫描的注解
@ComponentScan.Filter(type= FilterType.ANNOTATION,value={Controller.class}),
                // 排除要扫描的指定类
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE,value={Service001.class})
})
public class SpringConfig {
@Bean(name="person2")
public Person person(){
return new Person();
}
}

2、带注解的类
package com.tools.controller;

import org.springframework.web.bind.annotation.RestController;

/**
* @auto dh
* @create 2020-04-25-13:20
*/
@RestController
public class Controller001 {
}

package com.tools.dao;

import org.springframework.stereotype.Repository;


/**
* @auto dh
* @create 2020-04-25-13:22
*/
@Repository
public class Dao001 {
}

package com.tools.service;

import org.springframework.stereotype.Service;

/**
* @auto dh
* @create 2020-04-25-13:23
*/
@Service
public class Service001 {
}

3、测试类
package com.test;

import com.configuration.SpringConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
* @auto dh
* @create 2020-04-25-11:02
*/
public class Test001 {
public static void main(String[] args) {
// ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
// 通过注入该配置文件类的字节码文件,生成对应的对象
AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);
String[] beanDefinition=ctx.getBeanDefinitionNames();
for(String bean:beanDefinition){
System.out.println("bean信息"+bean);
}
}
}
原文地址:https://www.cnblogs.com/kukai/p/12772873.html