问题
在应用开发过程中,需要排除某些注解下的bean,但是排除配置未生效!
package com.fjd.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/**
* 使用场景说明
* 这种配置表示:
* 扫描 com.fjd 包
* 排除所有被 @Service 注解的类
* 包含被 @Repository 注解的类(需单独导入)
* 使用 AspectJ 模式排除 com.fjd.dao 包及其子包
*/
@Configuration
@ComponentScan(
value = "com.fjd",
//includeFilters = @Filter(type = FilterType.ANNOTATION, classes = Repository.class),
excludeFilters = {@ComponentScan.Filter
(type = FilterType.ANNOTATION,
classes = Service.class) // 排除 @Service
// @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "com.fjd.dao..*") // 排除 DAO 包
}
)
public class SpringConfig {
// 其他配置...
}
仍能正常运行。
原因分析
- 组件扫描范围问题
确保被@Service注解的类确实位于com.fjd包或其子包下
检查是否有其他@ComponentScan配置覆盖了当前配置 - 依赖问题
确认项目中正确引入了spring-context依赖,版本与Spring Boot兼容
检查是否存在依赖冲突导致注解失效
问题解决
存在其他@ComponentScan配置覆盖了当前配置
注释其他配置扫描,配置生效!