使用@componentscan注解中的@componentscan.filter标记不加载。
@componentscan(excludefilters = {@componentscan.filter(type = filtertype.aspectj, pattern ={"包名"})})@componentscan(excludefilters = {@componentscan.filter(type = filtertype.assignable_type,classes = 类名.class)})实现beanfactorypostprocessor接口,编译完毕后删除 (当然这里你也可以写一个配置类)
@springbootapplication
public class empserviceapplication implements beanfactorypostprocessor {
public static void main(string[] args) {
springapplication.run(empserviceapplication.class, args);
}
@override
public void postprocessbeanfactory(configurablelistablebeanfactory beanfactory) throws beansexception {
// 检查是否是 beandefinitionregistry
if (beanfactory instanceof beandefinitionregistry) {
beandefinitionregistry registry = (beandefinitionregistry) beanfactory;
// 获取所有bean的名称
string[] beannames = beanfactory.getbeandefinitionnames();
for (string beanname : beannames) {
// 获取bean的定义
beandefinition beandefinition = beanfactory.getbeandefinition(beanname);
// 获取bean的类名
string beanclassname = beandefinition.getbeanclassname();
// 自定义排除逻辑
if (beanclassname != null && beanclassname.startswith("包名")) {
// 移除不需要的bean
registry.removebeandefinition(beanname);
system.out.println("excluded bean: " + beanname);
}}}
else {
throw new illegalstateexception("beanfactory is not a beandefinitionregistry");
}
}
}使用@componentscan,配合自定义过滤器,实现typefilter接口,指定不编译不加载某些bean
@springbootapplication
@componentscan(excludefilters = @componentscan.filter(
// 使用自定义过滤器
type = filtertype.custom,
// 指定自定义过滤器类
classes = customexcludefilter.class))
public class serviceapplication{
public static void main(string[] args) {
springapplication.run(serviceapplication.class, args);
}
}
}import org.springframework.core.type.classreading.metadatareader;
import org.springframework.core.type.classreading.metadatareaderfactory;
import org.springframework.core.type.filter.typefilter;
/**
* @description: 自定义排除过滤器:实现自定义的排除逻辑,返回true表示排除该类,返回false表示包含该类。
* @version: 1.0
**/
public class customexcludefilter implements typefilter {
@override
public boolean match(metadatareader metadatareader, metadatareaderfactory metadatareaderfactory) {
// 在这里实现自定义的排除逻辑。例如,根据类的名称、包名或其他属性来决定是否排除该类。这里获得是类的全限定名。版本升级请注意
string classname = metadatareader.getclassmetadata().getclassname();
if (classname != null && classname.startswith("包名")) {
// 返回true表示排除该类。
return true;
}
// 返回false表示包含该类。
return false;
}
}到此这篇关于springboot项目删除bean或者不加载bean的文章就介绍到这了,更多相关springboot项目不加载bean内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论